Search code examples
javascriptjqueryimage-loading

Load all images inside a class


I am loading 52 images that share the same class, when printing the loaded images to the console the amount of images that are outputting change each time I refresh.

The desired output would be to load every image in the class, as I am trying to tracking the progress with a progress bar then display the image gallery.

var thumbs = document.getElementsByClassName("thumbImg");
var thumbTotal = thumbs.length;
console.log("number of thumbImg's = ", thumbTotal);

$(".thumbImg").on("load", function() {
    console.log("the following has loaded = ",this);
});

This outputs the following showing the random amount of images loaded.

1/2

2/2


Solution

  • May be due to browser caching. You can try checking each image's .complete property, and run the code immediately if already complete.

    $(".thumbImg").each(function(i, el) {
      if (el.complete) {
        handler.call(el);
      } else {
        $(el).on("load", handler);
      }
    })
    
    function handler() {
        console.log("the following has loaded = ",this);
    }