I'm realoading a <div>
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 now i have this:
$(document).ready(function(){
$("img").load(function(){
alert("ok?");
});
});
but with this i keep getting an alet for every image on this partial....
i don't know iuf there's a selector like $(allimgs)
or something like that, what do i have to do to catch when all images are loaded?
Many Thanks.
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 */});
});
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();
});
});
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 ...
} });