頁面圖片一多,首次載入就會又慢又耗流量。延遲載入的}}) 思路很簡單:先把真實圖片網址藏在自訂屬性裡,等使用者捲動到接近該圖時,再把網址換到 src 上觸發下載。這個原理用原生 JavaScript 就能實作,不必引入外掛。
1. HTML 上用自訂屬性保存真實網址
<img class="lazy" data-src="real-photo.jpg" src="placeholder.gif" alt="" />
2. 計算圖片距離頁面的位置
jQuery 的 offset().top 在原生寫法是:
img.getBoundingClientRect().top + (document.body.scrollTop || document.documentElement.scrollTop)
3. 判斷是否進入可視區域
justTop > scrollTop && offsetTop < (scrollTop + windowHeight)
其中 justTop 是圖片的 offsetTop 加上圖片高度,也就是圖片的底緣。
var doc = document;
for(var n = 0, i = this.oImg.length; n < i; n++){
var hSrc = this.oImg[n].getAttribute(this.sHolder_src);
if(hSrc){
var scrollTop = doc.body.scrollTop || doc.documentElement.scrollTop,
windowHeight = doc.documentElement.clientHeight,
offsetTop = this.oImg[n].getBoundingClientRect().top + scrollTop,
imgHeight = this.oImg[n].clientHeight,
justTop = offsetTop + imgHeight;
if(justTop > scrollTop && offsetTop < (scrollTop + windowHeight)){
this.isLoad(hSrc, n);
}
}
}
isLoad: function(src, n){
var o_img = new Image(),
_that = this;
o_img.onload = function(){
_that.oImg[n].setAttribute('src', src);
_that.oImg[n].removeAttribute(_that.sHolder_src);
};
o_img.src = src;
}
這裡用了一個的技巧:先建立一個脫離文件的 Image 物件預先下載,等 onload 觸發後才把網址設給畫面上真正的 img。因為圖片已在快取中,使用者不會看到「先出現破圖再變正常」的閃跳。
捲動事件觸發頻率極高,若每次都跑一遍迴圈會明顯卡頓。加上短暫的 setTimeout 合併連續觸發:
int: function(){
this.loadImg();
var _that = this, timer = null;
window.onscroll = function(){
clearTimeout(timer);
timer = setTimeout(function(){ _that.loadImg(); }, 100);
};
}
今天已經有原生 API 專門解決這件事,不必自己算座標、也不必監聽 scroll:
var observer = new IntersectionObserver(function(entries){
entries.forEach(function(entry){
if(entry.isIntersecting){
var img = entry.target;
img.src = img.dataset.src;
observer.unobserve(img);
}
});
}, { rootMargin: "200px" }); // 提前 200px 開始載入
document.querySelectorAll("img[data-src]").forEach(function(img){
observer.observe(img);
});
rootMargin 可以設定「提前多少距離開始載入」,讓圖片在使用者看到之前就載好,體驗更順。這個做法由瀏覽器原生最佳化,效能遠優於自行計算 getBoundingClientRect(後者會觸發強制重排)。
更進一步,<img loading="lazy"> 這個 HTML 屬性已可讓瀏覽器自動處理延遲載入,多數現代瀏覽器都支援。若加上 decoding="async" 與適當的 width/height 避免版面位移,通常就足夠了。
不過理解手動實作的原理仍有價值——當你需要「載入時播放骨架屏動畫」、「依網路速度決定載入品質」或「攔截載入失敗改用預設圖」這類客製行為時,Intersection Observer 搭配自訂 callback 就是必備工具。