懒加载的原理及实现

1.懒加载概念

对于页面有很多静态资源的情况下(比如网商购物页面),为了节省用户流量和提高页面性能,可以在用户浏览到当前资源的时候,再对资源进行请求和加载。

2.懒加载实现原理

2.1监听onscroll事件判断资源位置
首先为所有懒加载的静态资源添加自定义属性字段,比如如果是图片,可以指定data-src为真实的图片地址,src指向loading的图片。
然后当资源进入视口的时候,将src属性值替换成data-src的值。
可以使用元素的getBoundingRect().top判断是否在视口内,也可以使用元素距离文档顶部的距离offsetTop和scrollTop是否小于视口高度来判断:

window.onload=function(){

                var clientHeight=getWindow().height;
                //选取所有包含属性data-src的img元素,然后在滚动的时候判断是否在可视区域
                var imgArray=toArray(document.querySelectorAll("[data-src]"));

                function lazyLoad(){
                    var loadedIndex=[];

                    var scrollTop=document.body.scrollTop||document.documentElement.scrollTop;
                    for(let i=0;i<imgArray.length;i++){
                        let img=imgArray[i];
                        if(img.offsetTop-scrollTop<clientHeight){
                            img.src=img.getAttribute("data-src");
                            console.log("img "+img.src.substring(img.src.lastIndexOf("/")+1)+"display.");
                            loadedIndex.unshift(i);//这里不能用push,因为删除的时候先要删除后面的,再删除前面的,否则Array删除了前面的,后面的就会自动覆盖到前面来。
                        }
                    }

                    for(let i=0;i<loadedIndex.length;i++){
                        imgArray.splice(loadedIndex[i],1);
                    }
                }

                //跨浏览器获取可视窗口大小
                function  getWindow () {
                    if(typeof window.innerWidth !='undefined') {
                        return{
                            width : window.innerWidth,
                            height : window.innerHeight
                        }

                    } else{
                        return {
                            width :    document.documentElement.clientWidth,
                            height : document.documentElement.clientHeight
                        }
                    }
                }

                function toArray(arrlike){
                    if(typeof Array.from !="function"){
                        var result=[];
                        for(let i=0;i<arrlike.length;i++){
                            result.push(arrlike[i]);
                        }
                        return result;
                    }else{
                        return Array.from(arrlike);
                    }
                }

                window.onscroll=lazyLoad;
                lazyLoad();

            }

其中判断元素是否应该下载的语句是:

                    if(img.offsetTop-scrollTop<clientHeight){
                            img.src=img.getAttribute("data-src");
                            console.log("img "+img.src.substring(img.src.lastIndexOf("/")+1)+"display.");
                            loadedIndex.unshift(i);
                        }

或者是:

if(rect.top>=0&&rect.top<=clientHeight)

但是由于scroll事件密集发生,计算量很大,容易造成性能问题,因此不推荐使用。
2.2 浏览器API——IntersectionObserver
可以自动”观察”元素是否可见,Chrome 51+ 已经支持。由于可见(visible)的本质是,目标元素与视口产生一个交叉区,所以这个 API 叫做”交叉观察器”。但是IE11目前仍不支持。
caniuse

3.懒加载封装

利用IntersectionObserver API的插件:

3.1使用Jquery插件jquery_lazyload

Github地址:https://github.com/tuupola/jquery_lazyload
引入CDN:

<script src="https://cdn.jsdelivr.net/npm/lazyload@2.0.0-beta.2/lazyload.js"></script>
        </script>

为需要懒加载的图片添加lazyload类名,指定data-src为真实图片地址,src为缩略图地址,调用lazyload();

3.2阮一峰 lozad.js

https://github.com/ApoorvSaxena/lozad.js
这里写图片描述
可以引入模板使用,也可以直接使用CDN引入脚本文件:
CDN:

<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/lozad/dist/lozad.min.js"></script>

使用方法之一,对所有需要懒加载的图片添加”lozad”类名,然后使用以下脚本调用:

const observer = lozad(); // lazy loads elements with default selector as '.lozad'
observer.observe();

4.示例演示及三种方案源码

https://lucyzlu.github.io/Web/lazyload/lazyload.html

5.参考

IntersectionObserver API 使用教程
阮一峰:网页性能管理详解
廖雪峰:使用jQuery实现图片懒加载原理

  • 7
    点赞
  • 75
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值