Created
July 10, 2021 12:48
-
-
Save bluwy/ca4dd13820aea775fff86e6628580945 to your computer and use it in GitHub Desktop.
[Svelte] Reload image on fail to fetch
This file contains hidden or 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
export function reloadImgOnFail(img, opts = {}) { | |
opts = ensureOpts(opts) | |
let retryCount = 0 | |
function handleError() { | |
if (retryCount >= opts.maxRetryCount) { | |
if (opts.fallbackSrc && img.src !== opts.fallbackSrc) { | |
img.src = opts.fallbackSrc | |
} | |
} else { | |
setTimeout(() => (img.src = img.src), opts.getTimeout(retryCount++)) | |
} | |
} | |
function ensureOpts(o) { | |
return { | |
getTimeout: o.getTimeout ?? ((n) => n * n + 1), | |
maxRetryCount: o.maxRetryCount ?? 3, | |
fallbackSrc: o.fallbackSrc | |
} | |
} | |
img.addEventListener('error', handleError) | |
return { | |
update(newOpts = {}) { | |
opts = ensureOpts(newOpts) | |
}, | |
destroy() { | |
img.removeEventListener('error', handleError) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment