实现图片懒加载的两种方法

一,什么是懒加载?

一般情况下,当一个页面加载以后,图片也会开始全部加载,这样会增加客户端和服务器的压力。为了减轻负担,让图片先出现在浏览器视口以后再进行加载。



方法一,使用三个相关API:

1,获取可视区域的高度 document.documentElement.clientHeight

2,获取元素到文档顶部的高度 element.offsetTop

3,获取浏览器窗口顶部与文档顶部之间的距 document.documentElement.scrollTop


var imgs = document.querySelectorAll('.lazyload-img');


//循环获取直到页面顶部的高度
function getElementTop(element) {
    var actualTop = element.offsetTop;
    var current = element.offsetParent;
    while(current !== null) {
        actualTop += current.offsetTop;
        current = current.offsetParent;
    }
    return actualTop;
}


function lazyLoad(imgs) {
    var vh = document.documentElement.clientHeight;
    var st = document.documentElement.scrollTop || document.body.scrollTop;
    imgs.forEach((item, index) => {
        if (vh + st > getElementTop(imgs[index])) {
            imgs[index].src = imgs[index].getAttribute('data-src');
        }
    });
}


window.onload = window.onscroll = function () {
    lazyLoad(imgs);
}



方法二,使用一个相关API

getBoundingClientRect() //获取元素的大小及位置

{
  bottom: 667.515625
  height: 117.5
  left: 269.046875
  right: 489.9375
  top: 550.015625
  width: 220.890625
  x: 269.046875
  y: 550.015625
}


滚动条向下滚动的时候,bound.top值会越来越小,也就是图片到可视区顶部的距离也越来越小,所以当bound.top == clientHeight时,说明土片马上就要进入可视区了,即 bound.top<=clientHeight时,图片是在可视区域内的。


var imgs = document.querySelectorAll('.lazyload-img');

function lazyLoad() {
  imgs.forEach(function(el){
    var bound = el.getBoundingClientRect();
    if(bound.top <= window.innerHeight){
      console.log("el: ", el);
      el.src = el.dataset.src;
    }
  })
}

window.onload = window.onscroll = function () {
  lazyLoad();
}



修改时间 2021-07-02

声明:本站所有文章和图片,如无特殊说明,均为原创发布。商业转载请联系作者获得授权,非商业转载请注明出处。
真诚赞赏,手留余香
赞赏
随机推荐
MySQL 批量插入数据时如何解决重复问题
冒泡法排序
Node.js 的 URL 的模块
Node.js 使用 Jest 和 supertest 做接口测试
WordPress 常用接口
PHP curl 的用法
使用 MySQL 线程池对压力测试的影响
Linux apt 命令