Execute code only after all images have been loaded in JavaScript
๐
July 2, 2021
๐JavaScript
Today, weโll show you how to execute code only after all images have been loaded in JavaScript.
Checkout more articles on JavaScript
- How to get the web page size in JavaScript
- Math functions in JavaScript
- Validate Image Content in ReactJS
- Image upload in ReactJS
- How to save an image from a URL in PHP
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.
<script>
var imgList = document.images;
var len = imgList.length;
var imgCounter = 0;
[].forEach.call(imgList, function (img) {
if (img.complete) {
incrementImgCounter();
}
else {
img.addEventListener('load', incrementImgCounter, false);
}
});
function incrementImgCounter() {
imgCounter++;
if (imgCounter === len) {
console.log('All images loaded!');
}
}
</script>
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..!! ๐