本文實作的效果是:當向下捲動頁面、圖片進入可視區域時,才真正開始載入,藉此提升頁面效能。
(1)在 img 標籤中,把真實圖片網址放在自訂屬性裡,例如 lazy-src。
(2)取得 img 距離頁面的高度,原生寫法為:
img.getBoundingClientRect().top + document.body.scrollTop || document.documentElement.scrollTop
(3)判斷圖片位置是否落在可視區域內:當 justTop > scrollTop 且 offsetTop < (scrollTop + windowHeight) 時,即代表出現在可視範圍,其中 justTop 為圖片的 offsetTop 加上圖片高度。
// 將 document 存入變數,減少查詢次數
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);
}
}
}
function LGY_imgScrollLoad(option){
this.oImg = document.getElementById(option.wrapID).getElementsByTagName('img');
this.sHolder_src = option.holder_src;
this.int();
}
LGY_imgScrollLoad.prototype = {
loadImg:function(){
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 src = src, n = n, o_img = new Image(), _that = this;
o_img.onload = (function(n){
_that.oImg[n].setAttribute('src',src);
_that.oImg[n].removeAttribute(_that.sHolder_src);
})(n);
o_img.src = src;
},
int:function(){
this.loadImg();
var _that = this, timer = null;
// 滾動時加入定時器,避免頻繁呼叫 loadImg
window.onscroll = function(){
clearTimeout(timer);
timer = setTimeout(function(){ _that.loadImg(); },100);
}
}
}
效果圖:

以上就是本文的全部內容,實作效果一點也不遜於 jQuery 插件,程式碼還相當簡潔,推薦給大家參考。