Skip to content

Instantly share code, notes, and snippets.

@Tenderfeel
Created October 8, 2021 07:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tenderfeel/f3f7261d773ba286e4ae27a7ca1f8e12 to your computer and use it in GitHub Desktop.
Save Tenderfeel/f3f7261d773ba286e4ae27a7ca1f8e12 to your computer and use it in GitHub Desktop.
Simple Image Preloader
interface PreloaderOptions {
onProgress?: Function
}
interface ImageOption {
src: string
img: HTMLImageElement
}
// Simple Images Preloader
class Preloader {
public images: ImageOption[]
public total: number
private _count: number
private _options: PreloaderOptions
constructor(_options: PreloaderOptions) {
const defaultOptions = {
onProgress: () => {},
}
this.images = this.getImages()
this.total = this.images.length
this._count = 0
this._options = { ...defaultOptions, ..._options }
}
private getImages() {
const options = []
const images = document.querySelectorAll('img')
images.forEach(img => {
const src = img.getAttribute('data-src')
if (!src) return
options.push({ src, img })
})
return options
}
private async _loadImages() {
await Promise.all(
this.images.map(option => {
return new Promise(async resolve => {
let img = new Image()
img.src = option.src
img.onload = () => {
option.img.src = option.src
this._count++
this._options.onProgress(Math.round(this._count))
resolve(option)
}
img.onerror = err => {
console.error(`Failed to load image file - ${option.src}`)
this._count++
this._options.onProgress(Math.round(this._count))
resolve(option)
}
})
})
)
}
public start() {
return this._loadImages()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment