就是图片延迟加载,不少图片并不须要页面载入的时候就加载,当用户滑到该视图的时候再加载图片,避免打开网页时加载过多的资源。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
<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>
若是 元素在文档中的top < 滚轮滚动的距离 + 视图大小 则加载图片htm
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();
则 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();