Reputation: 5374
I'm trying to detect when all images in an array load and then calling a function. Works fine in all browsers but IE.
//Detect when all images load
for (var i = 0, cnt = 0; i < urls.length; i++){
var img = new Image();
if(nodeNames[i] == 'IMG'){
//the following line is the problem, according to IE
img.onload = myFunction;
img.src = urls[i];
}
else if(nodeNames[i] === 'DIV'){
setTimeout(myFunction(),1);
}else{
setTimeout(myFunction(),1);
}
}
function myFunction(){
//...lots of code
}
else{
loaded = 0;
for(var i = 0, len = slides.length; i < len; ++i){
slides[i].css({
'display':'none'
});
}
}
}
Upvotes: 3
Views: 343
Reputation: 39872
You can just use the document onload event.
https://developer.mozilla.org/en/DOM/window.onload
The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.
For individual image loads see jQuery's load event which is different from the identically named ajax load. This will execute when the image loads.
$('img').load( function() {
//do something
});
Update
I think this is what OP is after. This bit of code will get each img once it is completely loaded. Once it loads a new image is created based on it and inserted into a new area (say a slideshow). In this example fiddle you can see that the two largest images will usually end up at the end of the copied image list. I also used a settimeout to load a final image after three seconds and this should always up at the end.
$('img').load( function () {
var img = new Image();
img.src = $(this).attr('src');
$('#showonload').append(img);
});
Upvotes: 2