Javascript - Event listener for when all elements of class are loaded

Viewed 2114

Is there a way in Javascript to execute code once every element of type/class/tag etc. has been loaded?

Something like:

document.getElementsByClassName("test").addEventListener("onload", ()=> { executeStuffHere(); });

If not, is there a similar way to do this for images? (Execute code once all images have been loaded)

2 Answers

You'll need a loop. You could make a count of the number of images, then decrement each time an image loads. Inside the callback, call the final function once the count gets to 0.

const images = document.getElementsByClassName("test");
let imagesLeft = images.length;
for (const image of images) {
  image.addEventListener('load', () => {
    imagesLeft--;
    if (imagesLeft === 0) executeStuffHere();
  });
}

Note that .addEventListener("onload" will not work. You must use load.

You could also add error listeners if you want executeStuffHere to run once everything is finished, even if some errored.

If some images might already be loaded, check if they're .complete first before adding the listener (and if they are, decrement).

First you wait for DOMContentLoaded or ensure that document.readyState is interactive or loaded, then select all nodes maching the criteria you want, loop over them, and execute the code. The method document.querySelectorAll() returns a NodeList, which you can coerce into an array

The main thing to note here is you're not waiting for each node to load. You're waiting for the whole document to load and then iterating through the DOM tree.

const fireOnAllYeses = () => {

  Array.from(document.querySelectorAll('.yes')).forEach(domNode => {
    
    //  execute code here
    console.log( domNode.innerText );
    
  });
};


document.addEventListener('DOMContentLoaded', fireOnAllYeses);
<main>
   <div class="yes">I am yes 1</div>
   <div class="no">I am no 1</div>
   <div class="yes">I am yes 2</div>
   <div>I am some div</div>
</main>

Related