Skip to content

Instantly share code, notes, and snippets.

@keevee09
Forked from mattdesl/load-images.js
Created April 2, 2016 01:31
Show Gist options
  • Save keevee09/4cb6d97f6b95771c731aff3dece151d6 to your computer and use it in GitHub Desktop.
Save keevee09/4cb6d97f6b95771c731aff3dece151d6 to your computer and use it in GitHub Desktop.
load images in parallel
function loadImage(url, callback) {
var image = new Image();
image.onload = function() {
callback(null, image);
};
image.onerror = function() {
callback(new Error('Could not load image at ' + url));
};
image.src = url;
}
function loadImages(urls, callback) {
var returned = false;
var count = 0;
var result = new Array(urls.length);
urls.forEach(function(url, index) {
loadImage(url, function(error, item) {
if (returned) return;
if (error) {
returned = true;
return callback(error);
}
result[index] = item;
count++;
if (count === urls.length) {
return callback(null, result);
}
});
});
}
var imageUrls = ['one.png', 'two.png', 'three.png'];
loadImages(imageUrls, function(err, images) {
if (err) throw err;
console.log('All images loaded', images);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment