Skip to content

Instantly share code, notes, and snippets.

@Jeremboo
Created October 3, 2018 02:09
Show Gist options
  • Save Jeremboo/596286c66d1745736ab50a2af0f0669e to your computer and use it in GitHub Desktop.
Save Jeremboo/596286c66d1745736ab50a2af0f0669e to your computer and use it in GitHub Desktop.
Preload and Map images
class ImageManager {
constructor () {
this.wMap = new Map() // Remplace with weakMap ???
}
/**
* Load it before if it nessessary
* @param {String} url The image to load
* @return {Promise}
*/
addImage (url) {
return this._loadImage(url).then(img => {
this.wMap.set(url, img)
})
}
/**
* Return an <img>
* @param {String} url The image to load
*/
getImage (url) {
return this.wMap.get(url)
}
/**
* Remove an image saved into the list
*/
deleteImage (url) {
this.wMap.delete(url)
}
/**
* Load the image with promise
* @param {String} url The image to load
* @return {Promise} <img> or catch
*/
_loadImage (url) {
return new Promise((resolve, reject) => {
let downloadingImage = this.getImage(url)
if (downloadingImage) {
resolve(downloadingImage)
} else {
downloadingImage = new Image()
downloadingImage.onload = () => {
resolve(downloadingImage)
}
downloadingImage.onerror = reject
downloadingImage.crossOrigin = 'Anonymous'
downloadingImage.src = url
}
})
}
}
const imageManager = new ImageManager()
export default imageManager
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment