js实现图片的懒加载

懒加载是非常实用的提升网页性能的方式,当访问一个页面的时候,只显示可视区域内的图片,其它的图片只有出现在可视区域内的时候才会被请求加载。

我们现在用原生的js实现简单的图片懒加载,主要利用的原理就是先不给设置src,而是把图片的路径放在data-src中,等待图片被加载的时候将路径取出放到src中。

HTML代码

<div class="container">
  <div class="img-area">
    <img class="my-photo" alt="loading" data-src="img/img1.png">
  </div>
  <div class="img-area">
    <img class="my-photo" alt="loading" data-src="img/img2.png">
  </div>
  <div class="img-area">
    <img class="my-photo" alt="loading" data-src="img/img3.png">
  </div>
  <div class="img-area">
    <img class="my-photo" alt="loading" data-src="img/img4.png">
  </div>
  <div class="img-area">
    <img class="my-photo" alt="loading" data-src="img/img5.png">
  </div>
</div>

判断元素是否在可视区域

方法一:

  1. 获取屏幕可视区高度:document.documentElement.clientHeight
  2. 获取元素距顶部的高度:element.offsetTop
  3. 获取滚动高度:document.documentElement.scrollTop
  4. 若满足:2-3<1,那么元素就出现在可视区域

方法二:
1. 获取元素到可视区域顶部的距离:var bound = element.getBoundingClientRect()
2. 获取可视区域的高度:window.innerHeight
3. 若满足bound.top<=window.innerHeight,那么元素就出现在可视区域

方法三:

  1. 利用IntersectionObserver函数自动观察元素是否在可视区域内
var watch = new IntersectionObserver(callback,option);
//开始观察
watch.observe(el);
//停止观察
watch.unobserve(el);
//关闭观察器
watch.disconnect();

js代码

第一种很多人都用过,所以我们就用第二种写一下

//判断图片是否出现在可视区域内

function isInSight(el) {
        const bound = el.getBoundingClientRect();
        const clientHeight = window.innerHeight;
        return bound.top <= clientHeight + 100;
    }

//加载图片

let index = 0;
    function checkImgs() {
        const imgs = document.querySelectorAll('.my-photo');
        for( let i = index; i < imgs.length; i++){
            if(isInSight(imgs[i])){
                loadImg(imgs[i]);
                index = i;
            }
        }
    }

function loadImg(el) {
        if(!el.src){
            const source = el.dataset.src;
            el.src = source;
        }
    }

//函数节流

//函数节流是很重要的思想,可以防止过于频繁的操作dom

function throttle(fn,mustRun = 500) {
        const timer = null;
        let previous = null;
        return function () {
            const now = new Date();
            const context = this;
            const args = arguments;
            if(!previous){
                previous = now;
            }
            const remaining = now -previous;
            if(mustRun && remaining >= mustRun){
                fn.apply(context,args);
                previous = now;
            }
        }
    }

//调用函数
window.onload=checkImgs;
window.onscroll = throttle(checkImgs);


我们在用第三种方法写一个demo

function checkImgs() {
  const imgs = Array.from(document.querySelectorAll(".my-photo"));
  imgs.forEach(item => io.observe(item));
}

function loadImg(el) {
  if (!el.src) {
    const source = el.dataset.src;
    el.src = source;
  }
}

const io = new IntersectionObserver(ioes => {
  ioes.forEach(ioe => {
    const el = ioe.target;
    const intersectionRatio = ioe.intersectionRatio;
    if (intersectionRatio > 0 && intersectionRatio <= 1) {
      loadImg(el);
    }
    el.onload = el.onerror = () => io.unobserve(el);
  });
});
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值