萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

圖片加載進度實時顯示:預載入與進度條實現方案

核心思路

  1. 創建 Image 對象數組,設置 src 觸發下載。
  2. 監聽每張圖的 onload / onerror,計數已完成數量。
  3. 進度 = loaded / total * 100%,更新 UI。
  4. 全部完成後,將圖片插入文檔或回調業務邏輯。

完整封裝類

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)
});

HTML 結構

<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 對象無法獲取單文件進度。

注意事項

  • 圖片失敗仍計入已完成數,避免進度卡住。
  • 大量圖片建議分批加載(如每批 6 張),避免瀏覽器並發連接限制導致阻塞。
  • 配合 loading="lazy" 或 IntersectionObserver 實現可視區懶加載,首屏優先。
copyright © 萬盛學電腦網 all rights reserved