1

i got the code here a array like this var pics = ['1.jpg','2.jpg','3,jpg'];

loop throught the array

var j = 0; 
var(var i in pics){ 
$(document.createElement(img)).attr('src',pics[i]).load(function(){
    alert(pics[i]+'is loaded');
    j++;
})}

if(j == pics.length){
alert('fully loaded');}

but all i got is 3,jpg is loaded all the time, how to solve this? where am i wrong?

vikingmute
  • 412
  • 2
  • 10
  • 24
  • Big dupe: http://stackoverflow.com/questions/4857896/jquery-callback-after-all-images-in-dom-are-loaded http://stackoverflow.com/questions/5424055/check-if-images-are-loaded http://stackoverflow.com/questions/6488104/how-to-know-when-all-images-inside-a-specific-div-are-loaded http://stackoverflow.com/questions/5410580/jquery-function-execute-when-all-images-are-loaded – Diodeus - James MacFarlane Aug 19 '11 at 02:28

2 Answers2

1

That's because the .load event fires asynchronously. JavaScript will not wait for all the images to load before proceeding with the script execution, so you need to perform the test each time an image has loaded. I've made your code a bit more readable too.

var len = pics.length;
var loadCounter = 0;
for(var i = 0; i < len; i++) {
    $(document.createElement(img)).attr('src', pics[i]).load(function() {
        alert(pics[i] + 'is loaded');
        loadCounter++;
        if(loadCounter === len) {
            alert("all are loaded");   
        }
    });
}

Side note: traversing an array using for...in will yield nasty results. In particular, it will include all properties of Array, so in short, don't do it :) See for yourself.

Another thing, the load event may not fire in some browsers when the image has been cached. To avoid this problem, you can manually fire the .load event on each image which has its complete property set.

var len = pics.length;
var loadCounter = 0;
for(var i = 0; i < len; i++) {
    $(document.createElement(img)).attr('src', pics[i]).one("load", function() {
        alert(pics[i] + 'is loaded');
        loadCounter++;
        if(loadCounter === len) {
            alert("all are loaded");   
        }
    }).each(function() {
        if(this.complete) $(this).trigger("load");
    });
}
karim79
  • 339,989
  • 67
  • 413
  • 406
0

You need to scope the i variable to retain the current value in the loop.

var j = 0; 

for( var i = 0; i < pics.length; i++ ){ 
    addHandler( i );
}

function addHandler( this_i ) {

    $(document.createElement( 'img' )).attr('src',pics[i]).load(function(){
        alert(pics[this_i]+'is loaded');
        j++;

        if(j == pics.length){
            alert('fully loaded');
        }
    });

}
user113716
  • 318,772
  • 63
  • 451
  • 440