Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Can I sync up multiple image onload calls? Re: Can I sync up multiple image onload calls?

#93731
noahgelman
Participant

Here are 2 answers via stack overflow:

// loader will 'load' items by calling thingToDo for each item,
// before calling allDone when all the things to do have been done.
function loader(items, thingToDo, allDone) {
if (!items) {
// nothing to do.
return;
}

if ("undefined" === items.length) {
// convert single item to array.
items = [items];
}

var count = items.length;

// this callback counts down the things to do.
var thingToDoCompleted = function (items, i) {
count--;
if (0 == count) {
allDone(items);
}
};

for (var i = 0; i < items.length; i++) {
// 'do' each thing, and await callback.
thingToDo(items, i, thingToDoCompleted);
}
}

function loadImage(items, i, onComplete) {
var onLoad = function (e) {
e.target.removeEventListener("load", onLoad);

// this next line can be removed.
// only here to prove the image was loaded.
document.body.appendChild(e.target);

// notify that we're done.
onComplete(items, i);
}
var img = new Image();
img.addEventListener("load", onLoad, false);
img.src = items;
}

var items = ['http://bits.wikimedia.org/images/wikimedia-button.png',
'http://bits.wikimedia.org/skins-1.18/common/images/poweredby_mediawiki_88x31.png',
'http://upload.wikimedia.org/wikipedia/en/thumb/4/4a/Commons-logo.svg/30px-Commons-logo.svg.png',
'http://upload.wikimedia.org/wikipedia/commons/3/38/Icons_example.png'];

loader(items, loadImage, function () {
alert("done");
});

and here is a jsFiddle link for you http://jsfiddle.net/8baGb/1/
Second solution:

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;

And here is a link to the Stack Overflow thread