How does js or jq judge that all images have been loaded?

how does js or jq determine that all images have been loaded?

Mar.07,2021

use the onload event of document, or if you only care about pictures, hook up the load event of img.

$('img').on('load', function() {
    // xxx
});

 /**
 *
 * @param arr ['']
 * @returns {Array}
 */
function loadImg(arr) {
    var newimages = [];
    var arr = (typeof arr != "object") ? [arr] : arr  //
    for (var i = 0; i < arr.length; iPP) {
        newimages[i] = new Promise(function (resolve, reject) {
            var image = new Image();
            image.addEventListener('load', function listener() {
                resolve(image);
                this.removeEventListener('load', listener);
            });
            image.src = arr[i];
            image.addEventListener('error', reject);
        })
    }
    return newimages
}
Promise.all(loadImg(listPics)).then(function () {
    console.log('')
});

the processing scheme of loading all pictures used by the project before, I hope it can help you


onload event of js image, load of jq


then you need to know the number of pictures in advance. Add a counter in the load callback function

.
var i = 0;
$('img').load(function(){
    iPP;
    if(i==x){
        ...
    }
});

you need https://www.npmjs.com/package.

Menu