懒加载的实现以及优化(函数节流)

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);图片

相关文章
相关标签/搜索