Execute code only after all images have been loaded in JavaScript

Today, we’ll show you how to execute code only after all images have been loaded in JavaScript.

Sometimes, we need to check if all images are loaded or not in the browser. There is no default method to check when all images have been loaded in Javascript. So here we explain a simple way to know simultaneously when all images are loaded in Browser.

How it works

  • Load all the images in a variable from the document. (You can also use the querySelector to get the list of the images from the particular div)
  • Loop through these images.
  • Add a listener for the load event on each of these images to run the incrementImgCounter function.
  • The incrementImgCounter will increment the counter
  • If the counter has reached the length of images, that means they’re all loaded

Note: You can also handle the error event listener for broken images.

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂

If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *