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