Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross-browser solution for a callback when loading multiple images?

I checked other questions, but they all had information how to make a callback when one specific image has 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 with an 'if' statement. Also, $(window).load (or onLoad or whatever) doesn't work.

In my case I'm loading 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 gets executed when BOTH images have finished loading?

Thank you for your time.

like image 726
Nikolay Dyankov Avatar asked Dec 12 '22 06:12

Nikolay Dyankov


2 Answers

Here's a function that will create several images and call a callback when they are all 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);

P.S. whenever working with .onload for images, you must set the .onload handler before setting the .src value because the onload handler might fire immediately when setting the .src value if the image is in the cache. If you haven't set the onload handler first, then it may never fire because by the time you set the handler, the image is already loaded. This happens in some browsers. Just always set .onload before .src if you need the onload event.

like image 196
jfriend00 Avatar answered Dec 15 '22 00:12

jfriend00


It's called reference counting. It's the standard technique for running a single callback after n tasks have finished.

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

function callback() {

}
like image 27
Raynos Avatar answered Dec 15 '22 01:12

Raynos