Part of my HTML page is the following div
:
<div id="images_wrapper">
<img ... />
<img ... />
<img ... />
...
</div>
Initially, this div
is hidden, and I show it only when all images are loaded:
$(window).load(show_images_wrapper);
However, if I'm not mistaken, show_images_wrapper
will be called only when all the page is loaded. I would like show_images_wrapper
to be called as soon as all images inside images_wrapper
has been loaded, and don't wait until all the page is loaded.
I tried:
$("#images_wrapper").load(show_images_wrapper);
but it didn't work.
How should I do this ?
The image is considered completely loaded if any of the following are true: Neither the src nor the srcset attribute is specified. The srcset attribute is absent and the src attribute, while specified, is the empty string ( "" ). The image resource has been fully fetched and has been queued for rendering/compositing.
To check if an image is loaded successful or not, you can combine the use of jQuery 'load()' and 'error()' event : $('#image1') . load(function(){ $('#result1'). text('Image is loaded!
The document. ready() function will be executed as soon as the DOM is loaded. It will not wait for the resources like images, scripts, objects, iframes, etc to get loaded.
Set up a counter to the quantity of the images using the length
[docs] property, that is decremented as the images load.
var imgs = $("#images_wrapper > img").not(function() { return this.complete; });
var count = imgs.length;
if (count) {
imgs.load(function() {
count--;
if (!count) {
$("#images_wrapper").show();
alert('all done');
}
});
} else {
$("#images_wrapper").show();
}
The the not()
[docs] method is removing from the matched set the images where their .complete
property is true
. This means the image has already downloaded, and was perhaps cached by bhe browser.
Of course the load()
[docs] method fires as each image finishes loading.
Example: http://jsfiddle.net/uhmAR/1/
EDIT: Changed it so that the container will show if all the images happened to be cached.
EDIT:
Another variation on the above is to bind the .load()
to all the images, and use the filter()
[docs] method to get the ones that are .complete
, and just manually invoke the .load()
on them.
This removes the need for the if/else
statement.
var imgs = $("#images_wrapper > img")
var count = imgs.length;
imgs.load(function() {
count--;
if (!count) {
$("#images_wrapper").show();
alert('all done');
}
}).filter(function() { return this.complete; }).load();
Example: http://jsfiddle.net/uhmAR/3/
I wrote a jQuery plugin that can do this.
$('#images_wrapper').waitForImages(function() {
// Done.
});
Alternatively,
var images = $('#images_wrapper img'),
imagesLength = images.length;
images.load(function() {
if ( ! --imagesLength) {
// Done.
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With