I want to load every image inside a div before actually displaying them. I have something similar to this:
<div>
<img src="1.jpg" />
<img src="1.jpg" />
<img src="1.jpg" />
<img src="1.jpg" />
<img src="1.jpg" />
<img src="1.jpg" />
</div>
At first I tried doing things like:
$('div img').load(function() {
$('div img').show();
});
Or this:
$('div').find('img').load(function() {
$('div img').show();
});
Unfortunately, this didn't work because once the browser loads even just a single image, it fires the event. Any ideas on how to load everything first ? Thanks!
You can keep track of how many images have loaded:
var $images = $('div img'),
preloaded = 0,
total = $images.length;
$images.load(function() {
if (++preloaded === total) {
// Done!
}
});
Unfortunately there is not easy way to do this in a cross browser compatible way. But luckily there are 2 plugins out there that can make it painless.
Check out waitforimages and imagesloaded
Then you can do:
$('div').waitForImages(function(){
$(this).find('img').show();
});
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