Skip to content

Instantly share code, notes, and snippets.

@tregoning
Last active March 14, 2019 00:19
Show Gist options
  • Save tregoning/e8eb757cfcf283da6639d600d7f09ce3 to your computer and use it in GitHub Desktop.
Save tregoning/e8eb757cfcf283da6639d600d7f09ce3 to your computer and use it in GitHub Desktop.
preload image as a promise #img #promise
/**
* 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