There is a block in which there are pictures. After downloading all the pictures in the block, you need to perform the function. How do I know that all the pictures in the block are uploaded?

  • one
    subscribe to the onload in pictures - Grundy
  • one
    on jq $('.div img').load(function() { // загрузились }); - Alexander Igorevich
  • @AlexanderIgorevich, in this case, the load can be called but not the event hanger - Grundy

2 answers 2

In general, there are several options:

1) there is a plugin against cyclists: https://github.com/desandro/imagesloaded

2) or maybe somehow?

 var def = []; $promise = $('img').on('load', function() { this.def.resolve(); }) .attr("src", function() { this.def = $.Deferred(); def.push(this.def); return this.src; }).promise().done(function() { $.when.apply($, def).done(function( ajaxResult ){ console.log('images is load'); }); }); 

3) but in order not to change the src attribute, maybe add a function to the onload image?

 <img onload="this.setAttribute('loaded', 'loaded')"> $('img:not([loaded=loaded])')... 

    You can subscribe to the onload for all images, raise the counter after loading each image and call the function when all are loaded.

     var block = document.getElementById("block"); bindImagesOnload(block, function() { console.log("Все картинки загружены!"); }); function bindImagesOnload(node, fn) { var imgs = node.getElementsByTagName("img"), length = imgs.length; var counter = 0; var onload = function() { counter++; if (counter >= length) fn(); }; for (var i = 0; i < length; i++) { imgs[i].onload = onload; } } 
     <div id="block"> <img src="//www.google.com/logos/doodles/2015/thanksgiving-2015-6462359094689792-hp.jpg"> <img src="//www.google.ru/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"> <img src="//www.google.cn/landing/cnexp/google-search.png"> </div> 

    • this is only if at the time of calling bindImagesOnload all the img tags are already there - Grundy
    • @Grundy Yes, and still only when there are no downloaded pictures (otherwise it considers it wrong). - Peter Olson Nov.
    • and shouldn't it, if onload has already passed - just call the handler function right away? - Grundy
    • @Grundy How do I know if onload has already passed? - Peter Olson
    • In general, @PeterOlson is still the easiest way to install src images only after adding a load event handler. - Regent