預加載是提升使用者體驗的經典手法。把圖片提前載入瀏覽器快取,使用者後續瀏覽時就能免去等待,對圖片比例高的網站(攝影集、電商商品頁、藝廊)效果尤其明顯。本文介紹三種實作技術,並深入說明幾個容易踩到的相容性陷阱。
純 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 套到 XHTML 元素上,瀏覽器就會下載這些圖片。只要路徑維持不變,之後在頁面其他地方呼叫同一張圖時,瀏覽器會直接使用快取中的版本。簡單、不需要 JavaScript。
但這個做法有個缺點:預加載的圖片會與頁面其他內容一起下載,拉長整體載入時間。解法是用 JavaScript 把預加載延後到頁面載入完成之後:
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() 延後執行時機。若使用者的瀏覽器無法執行 JavaScript,圖片就是不預加載,頁面調用時正常顯示即可——這是一種合理的降級行為。
補充一個現代寫法:addLoadEvent 是為了避開直接指派 window.onload 會覆蓋既有處理器的問題。今天直接用 window.addEventListener('load', preloader) 即可,語意更清楚也不會互相干擾。
上述方法在某些情境下實作起來繁瑣,純 JavaScript 版本反而更直接。以下兩種寫法在所有現代瀏覽器上都能運作。
寫法 A:用 arguments 批次處理
<div class="hidden">
<script type="text/javascript">
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>
這個做法特別適合大量圖片。只要編輯、載入需要的路徑即可。一個實用的技巧是把它放在登入頁:使用者輸入帳號的那段時間, Gallery 的圖片多半已經預加載完成。
要注意的是,images 陣列必須持續存在(不能是函式內的區域變數且函式返回後失去參照),否則 Image 物件可能被回收而中斷下載。範例把它放在全域正是這個原因。
寫法 B:逐一宣告
<div class="hidden">
<script type="text/javascript">
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>
每張圖一個變數與一行 src 指派,模式固定,依需求擴充即可。
同樣可以封裝進函式並用 load 事件延後執行:
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);
不過要留意,函式版本中的 img1 等變數是區域變數,函式返回後就失去參照。實務上多數瀏覽器仍會完成已開始的下載,但為了保險,建議改用寫法 A 的陣列形式並把陣列放在外層。
這個方法不只預加載圖片,還能預加載 CSS 與 JavaScript。相較於直接建立 DOM 元素,Ajax 的優勢在於載入的檔案不會實際套用到當前頁面。
window.onload = function() {
setTimeout(function() {
// 用 XHR 取得 JS 與 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('');
// 預加載圖片
new Image().src = "https://domain.tld/preload.png";
}, 1000);
};
上面預加載了 preload.js、preload.css 與 preload.png。1000 毫秒的延時是為了避免腳本阻塞,導致正常頁面功能受影響。
若改用 DOM 建立元素的方式:
window.onload = function() {
setTimeout(function() {
var head = document.getElementsByTagName('head')[0];
// 建立新的 CSS
var css = document.createElement('link');
css.type = "text/css";
css.rel = "stylesheet";
css.href = "https://domain.tld/preload.css";
// 建立新的 JS
var js = document.createElement("script");
js.type = "text/javascript";
js.src = "https://domain.tld/preload.js";
head.appendChild(css);
head.appendChild(js);
// 預加載圖片
new Image().src = "https://domain.tld/preload.png";
}, 1000);
};
這裡透過 DOM 建立三個元素來完成三個檔案的預加載。使用 Ajax 的差別在於,載入的檔案不會被套用到頁面上,僅進入快取——這一點是 Ajax 相對 DOM 方式的優勢。
最直覺的寫法是这样的:
function loadImage(url, callback) {
var img = new Image();
img.src = url;
img.onload = function() {
// 圖片下載完畢時呼叫 callback
callback.call(img); // 把 callback 的 this 指向 img
};
}
在 Firefox 中測試完全正常,圖片下載後就會彈出它的寬度,無論點擊多少次或重新整理都一樣。
但換到 IE 就不對了。第一次載入同樣會彈出寬度,可是再點一次卻完全沒有反應,重新整理也一樣。
經過多個瀏覽器版本測試可以確認:IE6 與 Opera 有這個問題,Firefox 與 Safari 則表現正常。
原因在於快取。當圖片已經載入過一次,後續對同一張圖片的請求不會再發出新的 HTTP 請求,而是直接從快取讀取。Firefox 與 Safari 會讓這兩種載入方式對使用者透明,同樣觸發 onload 事件;IE 與 Opera 則忽略了這種一致性,從快取載入時不會觸發 onload,於是回呼函式永遠不被執行。
理想中的解法是 Image 物件能有一個狀態值,表明它是否已載入成功——從快取讀取時因為不需等待,狀態直接是「已完成」;從網路載入時則顯示「未完成」。
經過嘗試,可以找到一個各瀏覽器都支援的屬性:complete。因此在設定 onload 之前先判斷這個值即可:
function loadImage(url, callback) {
var img = new Image();
img.src = url; // 建立 Image 物件,實作圖片預下載
if (img.complete) {
// 圖片已在快取中,直接呼叫回呼
callback.call(img);
return; // 不必再處理 onload
}
img.onload = function() {
// 圖片下載完畢時呼叫回呼
callback.call(img); // 將回呼的 this 替換為 Image 物件
};
}
程式碼很短,但很實用。這裡有個順序上的細節值得說明:img.src 必須在 onload 之前設定,因為若圖片來自快取,src 指派後可能立刻同步完成,此時後設定的 onload 就永遠不會被觸發。範例用 img.complete 檢查正好繞過了這個問題,但更嚴謹的做法是先綁定 onload 再設定 src。
lightbox 類的效果為了讓圖片置中顯示,往往需要預加載並等到完全載入才顯示,體驗不算好(例如 Flickr 相簿的全螢幕模式)。一般認為 JavaScript 無法取得 img 的檔案頭數據,真的是這樣嗎?以下用一個巧妙的方法繞過它。
最常見的寫法如下:
var imgLoad = function(url, callback) {
var img = new Image();
img.src = url;
if (img.complete) {
callback(img.width, img.height);
} else {
img.onload = function() {
callback(img.width, img.height);
img.onload = null;
};
}
};
可以看到,這裡必須等圖片完全載入才能取得尺寸,速度不理想。
Web 應用有別於桌面應用,回應速度才是最好的使用者體驗。若想兼得速度與優雅,就必須提前取得尺寸。
關鍵觀察是:瀏覽器載入圖片時,你會看到它先佔好一塊版面、然後才慢慢填入內容,而且不需要預先設定 width 與 height——因為瀏覽器已經讀到了圖片的頭部數據。基於這個事實,只要用 JavaScript 定時偵測圖片的尺寸狀態,就能得知尺寸何時就緒。
實作中會遇到幾個相容性陷阱:width 與 height 的偵測方式在各瀏覽器並不一致;另外 WebKit 系瀏覽器中用 new Image() 建立的物件,會受到同一 url 仍在載入中的既有圖片影響。經過反覆測試後的最佳處理方式如下:
// 更新紀錄:
// 05.27: 1、保證回呼執行順序:error > ready > load;2、回呼函式 this 指向 img 本身
// 04-02: 1、增加圖片完全載入後的回呼 2、提升效能
/**
* 圖片頭數據載入就緒事件 —— 更快取得圖片尺寸
* @version 2011.05.27
* @param {String} 圖片路徑
* @param {Function} 尺寸就緒
* @param {Function} 載入完畢(可選)
* @param {Function} 載入錯誤(可選)
* @example
* imgReady('https://www.google.com.hk/intl/zh-CN/images/logo_cn.png', function () {
* alert('size ready: width=' + this.width + '; height=' + this.height);
* });
*/
var imgReady = (function () {
var list = [], intervalId = null,
// 用來執行佇列
tick = function () {
var i = 0;
for (; i < list.length; i++) {
list[i].end ? list.splice(i--, 1) : list[i]();
}
!list.length && stop();
},
// 停止所有定時器佇列
stop = function () {
clearInterval(intervalId);
intervalId = null;
};
return function (url, ready, load, error) {
var onready, width, height, newWidth, newHeight, img = new Image();
img.src = url;
// 如果圖片被快取,則直接回傳快取數據
if (img.complete) {
ready.call(img);
load && load.call(img);
return;
}
width = img.width;
height = img.height;
// 載入錯誤後的事件
img.onerror = function () {
error && error.call(img);
onready.end = true;
img = img.onload = img.onerror = null;
};
// 圖片尺寸就緒
onready = function () {
newWidth = img.width;
newHeight = img.height;
if (newWidth !== width || newHeight !== height ||
// 如果圖片已在其他地方載入,可用面積檢測
newWidth * newHeight > 1024) {
ready.call(img);
onready.end = true;
}
};
onready();
// 完全載入完畢的事件
img.onload = function () {
// onload 在定時器時間差範圍內可能比 onready 快,
// 這裡進行檢查並保證 onready 優先執行
!onready.end && onready();
load && load.call(img);
// IE 的 gif 動畫會循環執行 onload,置空 onload 即可
img = img.onload = img.onerror = null;
};
// 加入佇列中定期執行
if (!onready.end) {
list.push(onready);
// 無論何時只允許出現一個定時器,減少瀏覽器效能損耗
if (intervalId === null) intervalId = setInterval(tick, 40);
}
};
})();
呼叫方式:
imgReady('https://www.google.com.hk/intl/zh-CN/images/logo_cn.png', function () {
alert('size ready: width=' + this.width + '; height=' + this.height);
});
這個方式取得攝影級照片尺寸的速度,往往是 onload 方式的幾十倍;而對網頁等級(800×600 以內)的圖片,幾乎是瞬間完成。
以上技術在正-legged HTML era 都是標準做法,理解它們有助於掌握瀏覽器快取與事件模型的運作。但若你今天要開新專案,有幾個更省事的原生方案:
使用 <link rel="preload">。這是瀏覽器原生的資源提示機制,會在解析 HTML 時就開始下載,比等 JS 執行更早,也不會阻塞渲染:
<link rel="preload" as="image" href="hero.jpg">
使用 new Image().decode()。ES2018 之後可以明確等待解碼完成,避開 onload 與 complete 的相容性難題:
const img = new Image();
img.src = url;
try {
await img.decode();
console.log(img.naturalWidth, img.naturalHeight);
} catch (e) {
// 載入失敗
}
使用 img.loading = "lazy" 反向操作。多數時候我們真正需要的其實是「延後載入」而非「提前載入」,原生 lazy loading 屬性能讓瀏覽器自行決定時機,效果通常比手刻更好。
至於取得尺寸,除了上述的 imgReady 技巧,也可以搭配 width/height 屬性明確標示,讓瀏覽器在實際下載前就能配置版面,避免累積版面位移(CLS)。
以上就是圖片預加載的技術整理與實務建議。