js实现懒加载

懒加载是什么

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

当页面一次性要加载不少资源的时候每每要用到懒加载chrome

图片加载原理

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

这里插播一个小知识点app

//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赋值给srccode

首先一个简单的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 < 滚轮滚动的距离 + 视图大小 则加载图片htm

  • 元素在文档中的位置: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();
相关文章
相关标签/搜索