Cross browser callback solution when loading multiple images?

I checked other questions, but they all had information on how to make a callback when one specific image was loaded:

var img = new Image(); img.src = "images/img.png"; if (!img.complete) { img.onload = function() { // code to be executed when the image loads } } 

Or a simple check to see if all images are loaded using the if statement. Also, $ (window) .load (or onLoad or something else) doesn't work.

In my case, I upload two images:

 var img1 = new Image(); var img2 = new Image(); img1.src = 'images/img1.png'; img2.src = 'images/img2.png'; 

How can I define a callback similar to the one in the first example, but it is executed when the BOTH images finished loading?

Thank you for your time.

+4
source share
2 answers

Here is a function that will create multiple images and call a callback when they are loaded:

 function createImages(srcs, fn) { var imgs = [], img; var remaining = srcs.length; for (var i = 0; i < srcs.length; i++) { img = new Image(); imgs.push(img); img.onload = function() { --remaining; if (remaining == 0) { fn(srcs); } }; img.src = srcs[i]; } return(imgs); } var imgs = createImages(['images/img1.png', 'images/img2.png'], myCallback); 

PS When working with .onload for images, you must install the .onload handler before setting the .src value, because the onload handler can immediately work when you set the .src value if the image is in the cache. If you did not install the onload handler in the first place, it may never work, because by the time you install the handler, the image is already loaded. This happens in some browsers. Just set .onload to .src if you need the onload event.

+11
source

He called reference counting. This is the standard technique for starting a single callback after completing n tasks.

 var count = 2; img1.onload = function () { count-- === 0 && callback(); } img2.onload = function () { count-- === 0 && callback(); } function callback() { } 
+2
source

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


All Articles