Created
March 19, 2019 10:38
-
-
Save kribblo/7caa314d400e254827d075b740d3bb11 to your computer and use it in GitHub Desktop.
Minimal image loader with promises
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 imageLoader = { | |
/** | |
* Load a list of img URLs then resolve a Promise | |
* | |
* @param {String[]} urls images to load | |
* @param {Number} [retries=0] number of times to retry on img.onerror | |
* @return {Promise<HTMLImageElement[]|String>} return the loaded image elements in preserved order, or the first URL to fail on rejection | |
*/ | |
loadImages(urls, retries = 0) { | |
return new Promise((resolve, reject) => { | |
const images = []; | |
Promise.all(urls.map(url => this.loadImage(url, retries))) | |
.then(loaded => { | |
loaded.forEach(img => { | |
const position = urls.indexOf(img.url); | |
images[position] = img; | |
}); | |
resolve(images); | |
}).catch(reject); | |
}); | |
}, | |
/** | |
* Load an image URL then resolve a Promise | |
* | |
* @param {String[]} url image to load | |
* @param {Number} [retries=0] number of times to retry on img.onerror | |
* @return {Promise<HTMLImageElement|String>} return the loaded image element, or the URL that failed on rejection | |
*/ | |
loadImage(url, retries = 0) { | |
return new Promise((resolve, reject) => { | |
const img = new Image(); | |
img.onload = () => { | |
img.url = url; | |
resolve(img); | |
}; | |
img.onerror = () => { | |
retries--; | |
if(retries >= 0) { | |
return this.loadImage(url, retries); | |
} else { | |
reject(url); | |
} | |
}; | |
img.src = url; | |
}); | |
} | |
}; | |
module.exports = imageLoader; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment