vikingmute
vikingmute

Reputation: 412

how to check a array of imgs is fully loaded

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?

Upvotes: 1

Views: 1294

Answers (2)

user113716
user113716

Reputation: 322492

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');
        }
    });

}

Upvotes: 0

karim79
karim79

Reputation: 342635

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");
    });
}

Upvotes: 1

Related Questions