Created
October 8, 2021 07:30
-
-
Save Tenderfeel/f3f7261d773ba286e4ae27a7ca1f8e12 to your computer and use it in GitHub Desktop.
Simple Image Preloader
This file contains 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
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