3

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)

Voidableryzer
  • 161
  • 1
  • 8

2 Answers2

3

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).

CertainPerformance
  • 260,466
  • 31
  • 181
  • 209
  • Hi! Just a quick question, does this work for other elements too? I realised I don't have images, I have `div`s with `background-image`s. So far I've had no luck with this method, but I don't think it's a problem with your code, maybe just the way I'm using it – Voidableryzer Mar 13 '21 at 04:21
  • See https://stackoverflow.com/q/5057990 Only option looks to be to use `src` instead on an image, then change to `background-image` on the `
    ` once the image loads
    – CertainPerformance Mar 13 '21 at 04:25
0

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>
code_monk
  • 6,725
  • 2
  • 37
  • 34