Created
June 25, 2018 15:57
-
-
Save Troland/f0dcc59e6853cbe8386a9f921539a6a8 to your computer and use it in GitHub Desktop.
load images in parallel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const loadImage = (url, callback) => { | |
const image = new Image(); | |
image.onload = () => { | |
callback(null, image); | |
}; | |
image.onerror = () => { | |
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((url, index) => { | |
loadImage(url, (error, item) => { | |
if (returned) return; | |
if (error) { | |
returned = true; | |
return callback(error); | |
} | |
result[index] = item; | |
count++; | |
if (count === urls.length) { | |
return callback(null, result); | |
} | |
}); | |
}); | |
} | |
// const 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