Skip to content

Instantly share code, notes, and snippets.

@bluwy
Created July 10, 2021 12:48
Show Gist options
  • Save bluwy/ca4dd13820aea775fff86e6628580945 to your computer and use it in GitHub Desktop.
Save bluwy/ca4dd13820aea775fff86e6628580945 to your computer and use it in GitHub Desktop.
[Svelte] Reload image on fail to fetch
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