Jquery callback after loading all images in dom?

How can I fire an event when all images are loaded in the DOM? I searched a lot. I found this, but it does not work:

JQuery event for uploaded images

+42
jquery image load
Feb 01 2018-11-11T00:
source share
3 answers

Use the load() (docs) method of the window .

 $(window).load(function() { // this will fire after the entire page is loaded, including images }); 

Or just do it right through window.onload .

 window.onload = function() { // this will fire after the entire page is loaded, including images }; 



If you want to create a separate event for each image, put .load() on each image.

 $(function() { $('img').one('load',function() { // fire when image loads }); }); 

Or, if there is a chance that the image can be cached, do the following:

 $(function() { function imageLoaded() { // function to invoke for loaded image } $('img').each(function() { if( this.complete ) { imageLoaded.call( this ); } else { $(this).one('load', imageLoaded); } }); }); 



EDIT:

To perform an action after loading the last image, use the counter installed on the total number of images and decrease it each time the load handler is called.

When it reaches 0 , run another code.

 $(function() { function imageLoaded() { // function to invoke for loaded image // decrement the counter counter--; if( counter === 0 ) { // counter is 0 which means the last // one loaded, so do something else } } var images = $('img'); var counter = images.length; // initialize the counter images.each(function() { if( this.complete ) { imageLoaded.call( this ); } else { $(this).one('load', imageLoaded); } }); }); 
+104
Feb 01 2018-11-11T00:
source share

One problem that I encountered with the modified user113716 solution is that a broken image will keep the counter until it reaches 0. This fixed it for me.

 .error(function(){ imageLoaded(); $(this).hide(); }); 
+5
Sep 20 '13 at 20:23
source share

Below is what I came up with using deferred objects and $.when instead of using a counter.

 var deferreds = []; $('img').each(function() { if (!this.complete) { var deferred = $.Deferred(); $(this).one('load', deferred.resolve); deferreds.push(deferred); } }); $.when.apply($, deferreds).done(function() { /* things to do when all images loaded */ }); 

Let me know if there are any reservations.

+4
Jun 20 '17 at 12:21
source share



All Articles