图片懒加载js实现

1.懒加载原理

懒加载实现原理很简单,通过在img标签中设置一个H5自定义属性,在元素出现在可视区域时,替换默认的加载图片来达到效果

2.实现代码

// 定时器,300ms延迟后加载图片
let timer = null;
let loadingImgUrl =
  'https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1545210653&di=173f4d639097ddf9e69ed23cd0da47f9&src=http://img.mp.sohu.com/upload/20170720/cd59c28a4c6d49bc8b4ecfcdffbc04f1_th.png';
let loadingHeight = 0;
let n = 0;

function lazyload() {
  let imgs = document.getElementById('root').getElementsByTagName('img');
  // 获取可视窗口高度
  let viewHeight = document.documentElement.clientHeight;
  for (let i = 0; i < imgs.length; i++) {
    let img = imgs[i];
    // 获取图片离可视区域顶部的距离
    let top = img.getBoundingClientRect().top;
    if('false' == img.dataset.isLoaded && ((0 <= top && top <= viewHeight) || (top <= 0 && Math.abs(top) <= loadingHeight))) {
      // 打印1,2,...,9,10
      console.log(++n);
      // 替换src
      img.src = img.dataset.src;
      img.dataset.isLoaded = true;
    }
  }
}

let image = new Image();
image.src = loadingImgUrl;

// 先加载loading图片,避免获取的img标签top属性不正确
image.onload = function () {
  loadingHeight = image.height;
  lazyload();
}

window.addEventListener('scroll', function () {
  clearTimeout(timer);
  timer = setTimeout(function () {
    lazyload();
  }, 300);
})

你可能感兴趣的:(懒加载,javascript)