Image 對象數組,設置 src 觸發下載。onload / onerror,計數已完成數量。loaded / total * 100%,更新 UI。class ImagePreloader {
constructor(urls, options = {}) {
this.urls = urls;
this.onProgress = options.onProgress || (() => {});
this.onComplete = options.onComplete || (() => {});
this.onError = options.onError || (() => {});
this.loaded = 0;
this.total = urls.length;
this.images = [];
}
start() {
if (this.total === 0) { this.onComplete([]); return; }
this.urls.forEach((url, i) => {
const img = new Image();
img.onload = () => this.handleLoad(i, img);
img.onerror = () => this.handleError(i, url);
img.src = url;
this.images[i] = img;
});
}
handleLoad(index, img) {
this.loaded++;
this.onProgress(this.loaded / this.total, this.loaded, this.total, img);
if (this.loaded === this.total) {
this.onComplete(this.images);
}
}
handleError(index, url) {
this.loaded++;
this.onError(url, this.loaded / this.total);
if (this.loaded === this.total) {
this.onComplete(this.images);
}
}
// 靜態快捷方法
static load(urls, callbacks) {
const loader = new ImagePreloader(urls, callbacks);
loader.start();
return loader;
}
}
// 使用示例
const urls = [
'img/1.jpg', 'img/2.jpg', 'img/3.jpg', 'img/4.jpg', 'img/5.jpg', 'img/6.jpg'
];
ImagePreloader.load(urls, {
onProgress: (ratio, loaded, total, img) => {
document.getElementById('progress').textContent = Math.round(ratio * 100) + '%';
document.getElementById('bar').style.width = ratio * 100 + '%';
},
onComplete: (images) => {
const gallery = document.getElementById('gallery');
images.forEach(img => gallery.appendChild(img));
document.getElementById('loader').style.display = 'none';
},
onError: (url, ratio) => console.warn('加載失敗:', url)
});
<div id="loader">
<div class="progress-bar"><div id="bar"></div></div>
<span id="progress">0%</span>
</div>
<div id="gallery" style="display:flex; flex-wrap:wrap; gap:10px;"></div>
使用 XMLHttpRequest 或 fetch 獲取 blob,監聽 progress 事件可獲得單文件字節級進度,但要求圖片支持 CORS 且非 CDN 直鏈限制。普通 Image 對象無法獲取單文件進度。
loading="lazy" 或 IntersectionObserver 實現可視區懶加載,首屏優先。