Check if all images are uploaded

Here is my attempt to check if all images are uploaded:

for (var i = 0; i < imgCount; i ++) {
    loadArr[i] = false
    imgArr[i] = new Image()
    imgArr[i].src='img'+i+'.png'
    imgArr[i].onload = function() {
        loadArr[i] = true //but wait! At the end of
                          //the loop, i is imgCount
                          //so this doesn't work.
    }
}

The problem is that after the loop finishes, the variable iis equal imgCount. This means that all other “loaded” flags will never be set truewhen loading images.

Is there a way to add the “loaded” property to the image, or is there some workaround for this problem?

+5
source share
3 answers

You need to define the onload function using closure:

for (var i = 0; i < imgCount; i ++) {
    loadArr[i] = false
    imgArr[i] = new Image()
    imgArr[i].src='img'+i+'.png'
    imgArr[i].onload = (function(i){
        return function(){ loadArr[i] = true }
    })(i);
}

Here's a jsFiddle that demonstrates that this works in a similar scenario.

Also note that the solution you chose as the answer doesn't actually work:

imgArr[i].onload = (function() {
        loadArr[i] = true;
    })();

. , loadArr true, onload. :

imgArr[i].onload = loadArr[i] = true;
+7

, ,

for (var i = 0; i < imgCount; i++) {
    loadArr[i] = false
    imgArr[i] = new Image()
    imgArr[i].src = 'img' + i + '.png'
    imgArr[i].onload = function (index) {
        return function () {
            loadArr[index] = true //but wait! At the end of
            //the loop, i is imgCount
            //so this doesn't work.
        };
    }(i);
}
+1

! , . , == imgCount , "" . .

"" .

// Construct your image array
for (var i = 0; i < imgCount; i++) {
    imgArr[i] = new Image();
    imgArr[i].src='img'+i+'.png';
}

//Then iterate over the array, adding a 'loaded' attribute when it occurs
imgArr.each(function(){
    $(this).onload(function() {
        $(this).attr('loaded','true');
    });
}
-1

All Articles