Last active
December 18, 2019 20:59
-
-
Save devtin/a6a7040703acacbb0a1238ee4fdeb6b7 to your computer and use it in GitHub Desktop.
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
/** | |
* Pre-loads an image on the browser retrying in case of error. | |
* @param {String} src - Remote url | |
* @param {Number} [retries=3] - How many times to re-try in case of error | |
* @param {Number} [delay=300] - Amount of milliseconds to wait prior retrying in case of error. | |
* @return Promise.<HTMLElement> - Resolves the created image | |
* @throws {Error} - Once exhausted all `retries`, the last error thrown by the dom element | |
*/ | |
export function preloadImage (src, { retries = 3, delay = 300 } = {}) { | |
const img = document.createElement(`img`) | |
img.$retries = 0 | |
const retry = (reject) => { | |
if (img.$retries >= retries) { | |
return reject() | |
} | |
img.$retries++ | |
img.src = `${ src }${ src.indexOf('?') === -1 ? '?' : '&' }${ new Date() }` | |
} | |
return new Promise((resolve, reject) => { | |
img.src = src | |
img.onload = resolve.bind(null, img) | |
img.onerror = (err) => { | |
setTimeout(retry.bind(null, reject.bind(null, err)), delay) | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment