js实现懒加载

懒加载是什么

就是图片延迟加载,很多图片并不需要页面载入的时候就加载,当用户滑到该视图的时候再加载图片,避免打开网页时加载过多的资源。

当页面一次性要加载很多资源的时候往往要用到懒加载

图片加载原理

img标签有一个src属性,当src不为空时,浏览器就会根据这个值发请求

这里插播一个小知识点

//image对象写在脚本的时候不用插在文档中,就可以发送src中的请求
const img = document.createElement('img');
img.src = './1.jpg';
//script对象写在脚本的时候,要插在文档中才能发送src中的请求哦
const script = document.createElement('script');
script.src = './test.js';
document.body.appendChild(script);

懒加载实现

思路:首先将src属性临时保存在temp-src上,等到想要加载该图片时,再将temp-src赋值给src

首先一个简单的html结构
<div id="imgOuter">
    <div><img src="" temp-src="./1.JPG"></div>
    <div><img src="" temp-src="./2.JPG"></div>
    <div><img src="" temp-src="./3.JPG"></div>
    <div><img src="" temp-src="./4.JPG"></div>
    <div><img src="" temp-src="./5.JPG"></div>
    <div><img src="" temp-src="./6.JPG"></div>
</div>
代码实现
1. 通过获取元素在文档中的位置、滚轮滚动的距离、视图大小判断。

如果 元素在文档中的top < 滚轮滚动的距离 + 视图大小 则加载图片

  • 元素在文档中的位置:element.offsetTop
  • 滚轮滚动的距离:document.documentElement.scrollTop(IE和火狐) / document.body.scroolTop(chrome)
  • 视图大小: window.innerHeight (ie不可用)/document.documentElement.clientHeight (IE下为 浏览器可视部分高度/Chrome下为浏览器所有内容高度)
let imgList = Array.from(document.getElementById('imgOuter').children);
//可以加载区域=当前屏幕高度+滚动条已滚动高度
const hasheight = function(){
    const clientHeight = window.innerHeight;
    const top = document.documentElement.scrollTop || document.body.scrollTop;;
    return clientHeight+top;
}
//判断是否加载图片,如果加载则加载
const loadImage = function(){
    imgList.forEach(div => {
        const img = div.children[0];
        if(!img.src && div.offsetTop < hasheight()){
        //加载图片
            img.src = img.attributes['temp-src'].value;
        }
    });
}
//实时监听滚轮滑动判断是否需要加载图片
window.onscroll = function(){
    loadImage();
}
//首屏加载
loadImage();
2. 通过getBoundingClientRect()方法获取元素大小及位置实现
  • Element.getBoundingClientRect() 返回一个ClientRect的DOMRect对象
  • 对象包含top、right、botton、left、width、height值
  • top、right、botton、left 值都是相对于浏览器左上角而言

则 top< 当前视图的高度时 加载图片

let imgList = Array.from(document.getElementById('imgOuter').children);

//判断是否加载图片,如果加载则加载
const loadImage = function(){
    imgList.forEach(div => {
        const img = div.children[0];
        const clientHeight = window.innerHeight;
        const top = div.getBoundingClientRect().top;
        if(!img.src && top < clientHeight){
        //加载图片
            img.src = img.attributes['temp-src'].value;
        }
    });
}
//实时监听滚轮滑动判断是否需要加载图片
window.onscroll = function(){
    loadImage();
}
//首屏加载
loadImage();

转载于:https://my.oschina.net/u/2600761/blog/1524230

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值