Can I sync up multiple image onload calls?

Ark-of-Ice picture Ark-of-Ice · Dec 30, 2011 · Viewed 10.3k times · Source

I want a function to run when specific images are loaded, but I don't know how to wait for both to load before running. I only know how to chain them, like below:

Image1 = new Image();
Image1.src = 'image1-link.jpg';

Image2 = new Image();
Image2.src = 'image2-link.jpg';

Image1.onload = function() {
    Image2.onload = function() { ... }
}

The downside to this is it has to wait till Image1 completely loads before getting the second. I want to try something like this:

Image1 = new Image();
Image1.src = 'image1-link.jpg';

Image2 = new Image();
Image2.src = 'image2-link.jpg';

(Image1 && Image2).onload = function() { ... }

EDIT: Thank you both for the help Paul Grime and ziesemer. Both your answers are very good. I think I have to give the best answer to Paul Grime, although his uses more code, I only need to know the src of the images and the onload function is built in while in ziesemer's answer I need to know both the src, the count of the images, and have to write multiple onload lines.

Depending on the situation, both have their purpose. Thank you both for the help.

Answer

ziesemer picture ziesemer · Dec 30, 2011

If you can't use something like jQuery, create a helper function that you can pass to the onload of all your images you are interested in. Each time it is called, increment a counter, or add the src name to a set. Once the counter or your set reaches the size of all of the images that you are expecting, then you can fire off whatever work you really wanted to do.

Something like:

var imageCollector = function(expectedCount, completeFn){
  var receivedCount;
  return function(){
    if(++receivedCount == expectedCount){
      completeFn();
    }
  };
}();

var ic = imageCollector(2, function(){alert("Done!");});
Image1.onload = ic;
Image2.onload = ic;