var throttle = function (fn, interval){
var _self = fn, timer, firstTime = true;
return function(){
var args = arguments, _me = this;
if(firstTime){
_self.apply(_me, args);
return firstTime = false;
}
if(timer){
return false;
}app
timer = setTimeout(function(){
clearTimeout(timer);
timer = null;
_self.apply(_me, args);
}, interval || 500);
}
}
//懶加載代碼實現
var viewHeight = document.documentElement.clientHeight // 可視區域的高度
var i = 0;this
function lazyload () {
i++;
console.log(i)
// 獲取全部要進行懶加載的圖片
var eles = document.querySelectorAll('img[data-original][lazyload]')
Array.prototype.forEach.call(eles, function (item, index) {
var rect
if (item.dataset.original === '')
return
rect = item.getBoundingClientRect()
// console.log(rect)
// 圖片一進入可視區,動態加載
if (rect.bottom >= 0 && rect.top < viewHeight) {
!function () {
var img = new Image()
img.src = item.dataset.original
img.onload = function () {
item.src = img.src
}
item.removeAttribute('data-original')
item.removeAttribute('lazyload')
}()
}
})
}
// 首屏要人爲的調用,不然剛進入頁面不顯示圖片
lazyload()prototype
document.addEventListener('scroll', throttle(lazyload,200));
// document.addEventListener('scroll', lazyload);
console.log(i);圖片