DIV CSS 佈局教程網

圖片預先載入的三種實作:CSS、JavaScript 與 Ajax 全面比較
編輯:關於JavaScript     

預先載入(preload)的目的很單純:在使用者真正需要之前,就把圖片悄悄抓進瀏覽器快取。這樣當 Gallery 切換、tooltip 出現、hover 效果觸發時,畫面不會出現「一片空白等圖片」的尷尬。

實作方法有三大流派,各有取捨。本文逐一拆解,並附上實務上的優化建議。

方法一:純 CSS 預加載

最簡單的做法是把圖片掛到畫面外的背景位置上:

#preload-01 { background: url(https://domain.tld/image-01.png) no-repeat -9999px -9999px; }
#preload-02 { background: url(https://domain.tld/image-02.png) no-repeat -9999px -9999px; }
#preload-03 { background: url(https://domain.tld/image-03.png) no-repeat -9999px -9999px; }

把這三個 id 套到畫面上的元素,瀏覽器就會去抓這些圖片並放進快取。之後在頁面其他地方引用相同路徑時,直接從快取渲染。不需要一行 JavaScript,非常乾淨。

但這方法有個問題:預加載會和頁面其他資源一起搶頻寬,拖慢首屏。解法是把「設定背景」這件事延後到 window.onload 之後:

function preloader() {
  if (document.getElementById) {
    document.getElementById("preload-01").style.background = "url(https://domain.tld/image-01.png) no-repeat -9999px -9999px";
    document.getElementById("preload-02").style.background = "url(https://domain.tld/image-02.png) no-repeat -9999px -9999px";
    document.getElementById("preload-03").style.background = "url(https://domain.tld/image-03.png) no-repeat -9999px -9999px";
  }
}

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

addLoadEvent() 這個小工具值得記住:它不會覆蓋掉頁面上已有的 onload,而是把新函式串接上去。如果使用者的瀏覽器不支援 JavaScript,最壞情況就是圖片沒被預加載,頁面調用時正常顯示即可——不影響功能,只是少了優化,這是很好的降級特性。

方法二:純 JavaScript 預加載

用 Image() 建構子是最直觀的方式。

寫法 A:用 arguments 批次處理

<div class="hidden">
<script type="text/javascript">
<!--//--><![CDATA[//><!--
var images = new Array()
function preload() {
  for (i = 0; i < preload.arguments.length; i++) {
    images[i] = new Image()
    images[i].src = preload.arguments[i]
  }
}
preload(
  "https://domain.tld/gallery/image-001.jpg",
  "https://domain.tld/gallery/image-002.jpg",
  "https://domain.tld/gallery/image-003.jpg"
)
//--><!]]>
</script>
</div>

這種寫法特別適合大量圖片。只要往 preload() 的參數清單裡加路徑即可,不必改動任何邏輯。一個使用這技巧的畫廊站,登入頁就預載了五十多張圖,使用者輸入帳號的幾秒內背景已經準備好。

寫法 B:逐一宣告

<div class="hidden">
<script type="text/javascript">
<!--//--><![CDATA[//><!--
if (document.images) {
  img1 = new Image();
  img2 = new Image();
  img3 = new Image();
  img1.src = "https://domain.tld/path/to/image-001.gif";
  img2.src = "https://domain.tld/path/to/image-002.gif";
  img3.src = "https://domain.tld/path/to/image-003.gif";
}
//--><!]]>
</script>
</div>

模式很固定:一個 imgN = new Image() 搭配一行 imgN.src,照抄即可擴充。if (document.images) 是為了確認瀏覽器支援圖片,屬於舊時代的防禦性寫法。

寫法 B 的優化版:把整段包成函式,再用 addLoadEvent() 延後執行,同樣避開首屏搶頻寬:

function preloader() {
  if (document.images) {
    var img1 = new Image();
    var img2 = new Image();
    var img3 = new Image();
    img1.src = "https://domain.tld/path/to/image-001.gif";
    img2.src = "https://domain.tld/path/to/image-002.gif";
    img3.src = "https://domain.tld/path/to/image-003.gif";
  }
}

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

方法三:使用 Ajax 預加載

前面兩招都只處理圖片。Ajax 版本的好處是連 JS 與 CSS 都能一起預載,而且不會影響到目前頁面。

用 XMLHttpRequest:

window.onload = function() {
  setTimeout(function() {
    // XHR to request a JS and a CSS
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://domain.tld/preload.js');
    xhr.send('');

    xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://domain.tld/preload.css');
    xhr.send('');

    // preload image
    new Image().src = "https://domain.tld/preload.png";
  }, 1000);
};

這裡預加載了 preload.js、preload.css 與 preload.png。1000 毫秒的 setTimeout 是為了避開首屏關鍵期,避免腳本掛住而拖累正常頁面功能。

改用 DOM 建立元素:

window.onload = function() {
  setTimeout(function() {
    // reference to <head>
    var head = document.getElementsByTagName('head')[0];

    // a new CSS
    var css = document.createElement('link');
    css.type = "text/css";
    css.rel = "stylesheet";
    css.href = "https://domain.tld/preload.css";

    // a new JS
    var js = document.createElement("script");
    js.type = "text/javascript";
    js.src = "https://domain.tld/preload.js";

    // preload JS and CSS
    head.appendChild(css);
    head.appendChild(js);

    // preload image
    new Image().src = "https://domain.tld/preload.png";
  }, 1000);
};

關鍵差異在這裡:透過 XHR 或動態插入 link/script 載入,檔案進入快取但不會套用應用到目前頁面——CSS 不會覆蓋現有樣式、JS 不會執行副作用。這正是 Ajax 路線相對於前兩種方法的優勢。

該怎麼選?

只預載圖片,new Image() 最省事;需要連樣式與腳本一起準備,走 Ajax 或動態 DOM 插入;如果圖片數量多且不在首屏路徑上,CSS + addLoadEvent 延後設定背景是很優雅的折衷。三種方法可以並用,關鍵是千萬別讓預加載拖慢首屏——那是本末倒置。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved