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?
That’s because the
.loadevent 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.Side note: traversing an array using
for...inwill yield nasty results. In particular, it will include all properties ofArray, 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
.loadevent on each image which has itscompleteproperty set.