Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if all the images in the page are loaded

Tags:

javascript

The goal: check if all images in the page are loaded. If yes, call to a function, if not, again to check if all images are loaded.

My try:

let checkImages = new Promise(resolve => { resolve(areCompleted()); });

function areCompleted() {
  let images = document.querySelectorAll('img');
  images = Array.from(images);

  for (let i = 0; i < images.length; i++) {
    if (!images[i].complete) {
      return false;
    }
  }
  return true;
}

If all images are completed, it resolves the promise with true, if not, false.

checkImages.then(completed => {
  if (completed) {
    completedFunction();
  } else {
    // Check again
  }
});

If the response is true, call a function, if not... I don't know how to do the same check again, but I want to do that checking until the response is true.

like image 978
Angel Luis Avatar asked Sep 12 '25 01:09

Angel Luis


1 Answers

This function will check for already loaded images and attach an event listener to all the others so that it can tell when every image in a given container is loaded...

function onImagesLoaded(container, event) {
    var images = container.getElementsByTagName("img");
    var loaded = images.length;
    for (var i = 0; i < images.length; i++) {
        if (images[i].complete) {
            loaded--;
        }
        else {
            images[i].addEventListener("load", function() {
                loaded--;
                if (loaded == 0) {
                    event();
                }
            });
        }
        if (loaded == 0) {
            event();
        }
    }
}

var container = document.getElementById("container");

onImagesLoaded(container, function() {
    alert("All the images have loaded");
});
<div id="container">
  <img src="https://cdn.vox-cdn.com/thumbor/C1SdoDActSv8tPONx_OjwEobUjw=/0x0:1004x753/1200x800/filters:focal(0x0:1004x753)/cdn.vox-cdn.com/uploads/chorus_image/image/49523369/20150428-cloud-computing.0.jpg" />
  <img src="https://images.techhive.com/images/article/2016/08/clouds-100678070-primary.idge.jpg" />
  <img src="https://www.quali.com/wp-content/uploads/2016/04/101-HEADER-IMAGE.jpg" />
  <img src="https://cdn.computerworlduk.com/cmsdata/features/3641280/cloud_istock_malerapaso_thumb800.jpg" />
</div>

This will still work if all the images have already loaded, due to being cached, or if there are no images in the container.

If you want to check all images in a page, simply change the container selector to the body instead...

var container = document.getElementsByTagName("body")[0];
like image 132
Reinstate Monica Cellio Avatar answered Sep 14 '25 16:09

Reinstate Monica Cellio