如何使用 JavaScript 預載入影像?


preload 屬性指定作者認為頁面載入時媒體檔案應該如何載入。preload 屬性允許作者向瀏覽器提供有關載入頁面需要花費多少時間的提示,這將帶來最佳的使用者體驗。

Preload 還告訴瀏覽器您希望儘快載入的關鍵資源。這對於不容易感知的資源(例如樣式表中包含的字型、背景影像或從指令碼載入的資源)尤其有用。

使用preload 在這裡很有幫助,因為影像會提前開始載入,並且在瀏覽器需要顯示它時很可能已經存在。

JavaScript 中有幾種型別的影像預載入。

示例 1:在 JavaScript 中使用事件偵聽器

在以下示例中,我們正在預載入影像。如果影像在瀏覽器中完全載入,則它將顯示影像。

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Document</title>
</head>
<body>
   <p>onload Event</p>
   <img id="img1" src="https://tutorialspoint.tw/java/images/java-mini-logo.jpg" style="max-width: 50%;">
   <img id="img2" src="https://tutorialspoint.tw/javafx/images/javafx-mini-logo.jpg" style="max-width: 50%;" >
   <script>
      const img1 = document.getElementById("img1");
      const img2 = document.getElementById("img2");
      img1.addEventListener("load", function(){
         alert("first image is loaded");
      });
      img2.addEventListener("load", function(){
         alert("second image is loaded");
      })
   </script>
</body>
</html>

示例 2

在以下示例中,我們建立了兩個函式,第一個是 preloader(),第二個是 addLoadEvent(),並使用了 onload 事件偵聽器。

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Document</title>
</head>
<body>
   <img id="img1" src="https://tutorialspoint.tw/java/images/java-mini-logo.jpg" style="max-width: 20%" />
   <img id="img2" src="https://tutorialspoint.tw/javafx/images/javafx-mini-logo.jpg" style="max-width: 20%" />
   <script>
      function preloader() {
         if (document.getElementById) {
            document.getElementById("img1");
            document.getElementById("img2");
         }
      }
      function addLoadEvent(func) {
         var oldonload = window.onload;
         if (typeof window.onload != "function") {
            window.onload = func;
         } else {
            window.onload = function () {
               if (oldonload) {
                  oldonload();
               }
               func();
            };
         }
      }
      addLoadEvent(preloader);
   </script>
</body>
</html>

更新於: 2022年12月19日

1K+ 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.