How To Know When All Images From Document Did Load In Javascript?
I'm realoading a
content with an ajax function with Ruby On Rails i'm realoading a partial into a div and i want to know hot to know when all images have loaded because
Solution 1:
If you wish to ensure that all images loaded without errors you have to roll your own. If not you can use .load like already shown which will fire when the browser is done loading assets.
To roll your own, do something like this:
$(document).ready(function(){
var imgs = $("img"), cnt = imgs.length;
imgs
.load(function(){
if(!--cnt) {
/* all images loaded */
}
})
.error(function() { /* whoops an image failed to load */});
});
Solution 2:
Will do something like: First we count how many imgs we have in our page, every img load will decrement count by 1, and when it is 0, means that all images are loaded.
$(document).ready(function(){
var allimgs = $("img");
var count = allimgs.length;
allimgs.load(function(){
if(--count == 0) {
alert("all images are loaded");
}
})
});
**EDITED**
If the browser is caching the images, try this instead:
$(document).ready(function(){
var allimgs = $("img");
var count = allimgs.length;
$("img").one('load', function() {
count--;
if(count == 0) {
alert("all images are loaded");
}
}).each(function() {
if(this.complete) $(this).load();
});
});
Solution 3:
You might need to use the image loaded plugin, to ensure that your code deals with cached images etc. https://github.com/paulirish/jquery.imgloaded
and then your code
var total_number_of_images = $("img").length;
var loaded_images = 0;
$("img").load(function(){
loaded_images++;
if loaded_images = total_number_of_images {
// do something ...
} });
Post a Comment for "How To Know When All Images From Document Did Load In Javascript?"