Last active
March 14, 2019 00:19
-
-
Save tregoning/e8eb757cfcf283da6639d600d7f09ce3 to your computer and use it in GitHub Desktop.
preload image as a promise #img #promise
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
/** | |
* Returns a promise once an image has been preloaded successfully | |
* | |
* @param {String} url | |
* | |
* @returns {Promise} | |
*/ | |
const fetchImage = (url) => new Promise((resolve, reject) => { | |
const img = new Image(); | |
img.addEventListener('load', () => resolve(url), false); | |
img.addEventListener('error', e => reject(e), false); | |
img.setAttribute('src', url); | |
if (img.complete) { | |
resolve(url); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment