Last active
September 27, 2019 15:39
-
-
Save jvahldick/86813b21046b281c95682c2019331d4e to your computer and use it in GitHub Desktop.
Solving an issue with lazy load images or images that are been uploaded.
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
class ImageLoader { | |
DEFAULT_MAX_ATTEMPTS = 10; | |
DEFAULT_RELOAD_DELAY = 1000; | |
delay; | |
maxAttempts; | |
constructor(options) { | |
if (typeof options === 'undefined') { | |
options = {}; | |
} | |
this.maxAttempts = 'maxAttempts' in options ? options.maxAttempts : this.DEFAULT_MAX_ATTEMPTS; | |
this.delay = 'delay' in options ? options.delay : this.DEFAULT_RELOAD_DELAY; | |
} | |
wait() { | |
return new Promise(resolve => setTimeout(resolve, this.delay)); | |
} | |
retry(fn, attempt) { | |
let self = this; | |
if (!attempt) { | |
attempt = 1; | |
} | |
return new Promise((resolve, reject) => { | |
fn() | |
.then(resolve) | |
.catch(error => { | |
console.debug(`Error: "${error}"; Attempt ${attempt} of ${self.maxAttempts}`); | |
if (attempt >= self.maxAttempts) { | |
return reject(new Error(error)); | |
} | |
return self | |
.wait() | |
.then(() => { | |
self.retry(fn, ++attempt).then(resolve).catch(reject); | |
}) | |
; | |
}) | |
; | |
}); | |
} | |
persistLoad(targetImage) { | |
return this.retry(this.load(targetImage)); | |
} | |
load(targetImage) { | |
return () => { | |
return new Promise((resolve, reject) => { | |
const image = new Image(); | |
image.onload = () => { | |
resolve(targetImage); | |
}; | |
image.onerror = () => { | |
reject(new Error(`Image ${targetImage} could not be loaded.`)) | |
}; | |
image.src = targetImage; | |
}); | |
} | |
} | |
} | |
// Usage | |
(new ImageLoader()) | |
.persistLoad('my-image') | |
.then(() => { | |
console.log('image loaded'); | |
}) | |
.catch(() => { | |
console.log('image not loaded'); | |
}) | |
; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment