How to run a jQuery Code after loading all the images in my page ?
+1
A:
Checking to see that all images have loaded is slightly involved, so unless you have a pressing need to be so precise, it is much easier to check that all image and everything else has loaded:
$(window).load(function() { ... });
This makes use of the jQuery .load() method.
If you do really need to check for specifically only images, then things get a little trickier. I initially wanted to do this:
$("img").load(function() { ... }); \\ THIS IS INCORRECT!!!!!
However the above creates a jQuery object that contains all images, and then it binds function() { ... }
to each of these images. So the above will trigger a function as many times as there are images on the page!
To get around this, we should check how many images there are on the page, and only fire the function once after all those images have been loaded:
$(function() {
// To keep track of how many images have loaded
var loaded = 0;
// Let's retrieve how many images there are
var numImages = $("img").length;
// Let's bind a function to the loading of EACH image
$("img").load(function() {
// One more image has loaded
++loaded;
// Only if ALL the images have loaded
if (loaded === numImages) {
// This will be executed ONCE after all images are loaded.
function() { ... }
}
});
});
Peter Ajtai
2010-09-08 18:39:21
Since he wanted it only after *all* the images on the page have been loaded, I don't think this may pose a problem.
CD Sanchez
2010-09-08 18:42:42
@Daniel - Even if all the image are loaded from the browser cache (like for a previously visited page)? I'm not quite sure how the `load` is triggered in those cases.
Peter Ajtai
2010-09-08 18:51:27
@Peter Ajtai: I imagine so. There would still be other resources for the browser to load - and once they are loaded, the load event for the window will be fired. Even if every external resource is cached, I imagine it will still be fired once the page itself is done loading. I've yet to hear of the load event not firing in any valid case.
CD Sanchez
2010-09-08 19:01:56
+2
A:
$(function() {
var length = $('img').length ;
var counter = 0;
$('img').each(function() {
$(this).load(function(){
counter++;
if(counter == length) {
Callback(); //do stuff
}
});
});
});
Ninja Dude
2010-09-08 18:40:14
Heh, I hadn't realized what a pain this is. Though, you can remove a line by using `$("img").load()` instead of `$("img").each(function() { $(this).load() })`- See my edited answer.
Peter Ajtai
2010-09-08 20:10:36