How to verify when multiple images have been loaded in JavaScript | Our Code World

PHOTO EMBED

Sat Jul 30 2022 22:53:59 GMT+0000 (Coordinated Universal Time)

Saved by @gsinghg19 #javascript

// Create the flag variables (counter and total of images)
var Counter = 0;
var TotalImages = 2;

// Create an instance of your images
var Image1 = new Image();
var Image2 = new Image();

// Store the images that were not correctly loaded inside an array to show later
var notLoadedImages = [];

// The onload callback is triggered everytime an image is loaded
var onloadCallback = function(){
    // Increment the counter
    Counter++;

    // Verify if the counter is less than the number of images
    if(Counter < TotalImages){
        return;
    }

    // Trigger the final callback if is the last img
    allLoadedCallback();
};

// The onerror callback is triggered everytime an image couldn't be loaded
var onerrorCallback = function(){
    // Increment the counter
    Counter++;
    
    // Add the current image to the list of not loaded images
    notLoadedImages.push(this);

    // Verify if the counter is less than the number of images
    if(Counter < TotalImages){
        return;
    }

    // Trigger the final callback if is the last img
    allLoadedCallback();
};

// The callback that is executed when all the images have been loaded or not
var allLoadedCallback = function(){
    console.log("Atention, the following images were not loaded ", notLoadedImages);
};

// Attach onload callbacks
Image1.onload = onloadCallback;
Image2.onload = onloadCallback;

// Attach onerror callbacks
Image1.onerror = onerrorCallback;
Image2.onerror = onerrorCallback;

// Load the images !
Image1.src = "queso.png";
Image2.src = "image.jpg";
content_copyCOPY

https://ourcodeworld.com/articles/read/571/how-to-verify-when-multiple-images-have-been-loaded-in-javascript