電商與圖片密集的網站幾乎都採用延遲載入(lazy load):只載入使用者看得到的圖片,其餘等到接近可視區域時才抓。這篇文章拆解原理,並附一份可直接使用的外掛程式碼。
把圖片真實網址藏在自訂屬性裡,src 先放一張極小的佔位圖:
<img src="images/placeholder.png" lazy-src="images/realimg.jpg" alt="" />
<!-- 若瀏覽器停用 JavaScript,仍要讓圖片看得到 -->
<noscript><img src="images/realimg.jpg" alt="" /></noscript>
運作流程分三步:
本文的範例把整個 window 當成容器;若想在小範圍的捲動容器(例如側邊資訊列)中做同樣的事,把 container 換成該元素即可,原理不變。
(function ($) {
$.fn.imglazyload = function (options) {
var o = $.extend({
attr: 'lazy-src', // 存放真實網址的屬性名
container: window, // 容器
event: 'scroll', // 觸發事件
fadeIn: false, // 是否使用 fadeIn 呈現
threshold: 0, // 提前多少距離開始載入
vertical: true // true 為縱向,false 為橫向
}, options),
event = o.event,
vertical = o.vertical,
container = $(o.container),
threshold = o.threshold,
// 轉成 DOM 陣列以便 splice 移除
elems = $.makeArray($(this)),
dataName = 'imglazyload_offset',
OFFSET = vertical ? 'top' : 'left',
SCROLL = vertical ? 'scrollTop' : 'scrollLeft',
winSize = vertical ? container.height() : container.width(),
scrollCoord= container[SCROLL](),
docSize = winSize + scrollCoord;
// 觸發判斷器
var trigger = {
init: function (coord) {
return coord >= scrollCoord && coord <= (docSize + threshold);
},
scroll: function (coord) {
var scrollCoord = container[SCROLL]();
return coord >= scrollCoord && coord <= (winSize + scrollCoord + threshold);
},
resize: function (coord) {
var scrollCoord = container[SCROLL](),
winSize = vertical ? container.height() : container.width();
return coord >= scrollCoord && coord <= (winSize + scrollCoord + threshold);
}
};
var loader = function (triggerElem, event) {
var i = 0, isCustom = false, isTrigger, coord, elem, $elem, lazySrc;
// 自訂事件無需再判斷位置
if (event) {
if (event !== 'scroll' && event !== 'resize') { isCustom = true; }
} else {
event = 'init';
}
for (; i < elems.length; i++) {
isTrigger = false;
elem = elems[i];
$elem = $(elem);
lazySrc = $elem.attr(o.attr);
if (!lazySrc || elem.src === lazySrc) { continue; }
// 先讀快取,沒有才計算,避免重複 reflow
coord = $elem.data(dataName);
if (coord === undefined) {
coord = $elem.offset()[OFFSET];
$elem.data(dataName, coord);
}
isTrigger = isCustom || trigger[event](coord);
if (isTrigger) {
elem.src = lazySrc;
if (o.fadeIn) { $elem.hide().fadeIn(); }
$elem.removeData(dataName);
elems.splice(i--, 1); // 已處理的移出佇列
}
}
// 全部載入完成後卸除事件
if (!elems.length) {
if (triggerElem) { triggerElem.unbind(event, fire); }
else { container.unbind(o.event, fire); }
$(window).unbind('resize', fire);
elems = null;
}
};
var fire = function (e) { loader($(this), e.type); };
container = event === 'scroll' ? container : $(this);
container.bind(event, fire);
$(window).bind('resize', fire);
loader(); // 初始化
return this;
};
})(jQuery);
| 參數 | 型別 | 說明 |
|---|---|---|
| attr | string | 存放真實網址的屬性名,預設 lazy-src。 |
| container | dom / selector | 容器,預設 window,可自訂。 |
| event | string | 觸發載入的事件類型,預設 window 的 scroll。 |
| fadeIn | boolean | 是否用 fadeIn 效果顯示,預設 false。 |
| threshold | number | 距離圖片還有指定距離時就開始載入,預設 0。 |
| vertical | boolean | 是否縱向捲動,預設 true。 |
| loadScript | boolean | (增強版功能)是否以不阻塞方式載入 JavaScript 廣告圖片,預設 false。 |
offset() 會觸發 reflow,在 scroll 事件中每次都計算代價很高,因此把結果存進 data(),處理完再 removeData()。另外,現代瀏覽器已原生支援 loading="lazy" 屬性,簡單場景一行就能搞定;上面這套做法的價值在於需要自訂載入時機、淡入動畫或橫向捲動時仍然適用。