JavaScript 預載入影象

Harshit Jindal 2021年7月3日
JavaScript 預載入影象

本教程教授如何使用 JavaScript 預載入影象。

在談如何預載入圖片之前,我們先來了解一下為什麼需要預載入圖片。當我們在 HTML 中使用 <image> 標籤定義影象時,瀏覽器會看到該影象,下載它,並在頁面載入之前為我們快取它。它使顯示影象變得相當簡單。但是當我們有一些由 JavaScript 程式碼觸發的影象動態載入時,瀏覽器沒有關於它的先驗資訊。因此,此類影象無法下載和快取。這些影象將被即時載入,並且會在影象首先下載時導致顯示延遲。它使網站看起來很糟糕,因此必須預載入這些影象。

例如:如果我們要顯示滾動效果,即更改滑鼠在其上滾動時顯示的影象,我們必須確保第二張影象已預載入;否則,影象將花費大量時間載入,這會使網站看起來醜陋且反應遲鈍。

使用 JavaScript 預載入影象

程式

  • 啟動一個變數 preloaded 來儲存在預載入階段載入的影象數量和一個影象陣列 images 來儲存所有要預載入的影象的地址。
  • 我們定義了一個函式 preLoader() 來為所有必須預載入的影象建立影象物件,並將 src 屬性儲存在陣列 images 的物件上。我們還附加了一個函式 progress() 來維護成功預載入的影象數量,並在所有影象預載入後執行任何操作。
  • 我們向視窗新增一個事件偵聽器,在載入 DOM 內容時呼叫我們的 preLoader()

程式碼

var preloaded = 0;
var images = new Array("img1.jpg", "img2.jpg", "img3.jpg");
 
function preLoader(e) {
    for (var i = 0; i < images.length; i++) {
        var tempImage = new Image();
         
        tempImage.addEventListener("load", progress, true);
        tempImage.src = imageArray[i];
    }
}
 
function progress() {
    preloaded++;
     
    if (preloaded == imageArray.length) {
        //ALL Images have been loaded, perform the desired action
    }
}
this.addEventListener("DOMContentLoaded", preLoader, true);
作者: Harshit Jindal
Harshit Jindal avatar Harshit Jindal avatar

Harshit Jindal has done his Bachelors in Computer Science Engineering(2021) from DTU. He has always been a problem solver and now turned that into his profession. Currently working at M365 Cloud Security team(Torus) on Cloud Security Services and Datacenter Buildout Automation.

LinkedIn

相關文章 - JavaScript Image