JQuery Load all images inside a div before displaying

I want to load every image inside a div before actually displaying it. 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 to do things like:

 $('div img').load(function() { $('div img').show(); }); 

Or that:

 $('div').find('img').load(function() { $('div img').show(); }); 

Unfortunately, this did not work, because when the browser loads even one image, it fires an event. Any ideas on how to download everything first? Thanks!

+4
source share
5 answers

You can track how many images are uploaded:

 var $images = $('div img'), preloaded = 0, total = $images.length; $images.load(function() { if (++preloaded === total) { // Done! } }); 
+7
source

Unfortunately, this is not an easy way to do this in a cross browser. But, fortunately, there are 2 plugins that can make it painless.

Check out waitforimages and imagesloaded

Then you can do:

 $('div').waitForImages(function(){ $(this).find('img').show(); }); 
+1
source

Firstly, a modern browser can execute at the same time 6 request => Do not load so many images at boot time. If you have many images, you can set the images in the back 'src = "or non set" src "attributes, and after loading the first images

Secondly, you can check the "image upload" with

  document.getElementById('#imageId').complete == !0 

You can check the image with the largest size or the last image in the DOM to make sure that images of other images have been uploaded.

I hope he helps you.

0
source

This worked for me:

 $(document).ready(function () { $('#div with images').hide(); }); $(window).load(function () { $('#div with images').show(); }); 
0
source

Source: https://habr.com/ru/post/1438788/


All Articles