JavaScript 懒加载图片

来源:互联网 发布:哥伦比亚大学 知乎 编辑:程序博客网 时间:2024/05/17 06:27

1.什么是懒加载

当图片出现在可视区域时才加载图片。

2.懒加载实现方式

核心:可视区域(clientHeight)+滚动条距离顶部高度(scrollTop) > 元素到顶部距离(offsetTop)

0.获取元素到顶部的距离(offsetTop)
1.监听滚动
2.在滚动方法里,实时获取可视区域(clientHeight) 和 滚动条距离顶部高度(scrollTop)

3.对单个img进行懒加载

<!DOCTYPE html><html><head><meta charset="UTF-8"><title></title><style type="text/css">body{margin: 0px;}</style></head><body><div style="width: 100px;height: 100px;margin-top: 1200px;"><img data-src="img01.png" width="100px" height="100px" style="margin-top: 1200px;" id="img01"/></div><script type="text/javascript">var img01=document.getElementById('img01');window.onscroll=function () {//元素距离顶部的高度var oHeight=img01.offsetTop;//可视区域var height=document.documentElement.clientHeight;//滚动条距离顶部高度var scrollTop=document.documentElement.scrollTop||document.body.scrollTop;if (height+scrollTop>oHeight) {img01.src=img01.getAttribute("data-src");}}</script></body></html>

4.对多个标签进行懒加载

在需要懒加载的img标签的class属性添加上“lazyLoad”
<!DOCTYPE html><html><head><meta charset="UTF-8"><title></title><style type="text/css">body{margin: 0px;}</style></head><body><div style="width: 100px;height: 100px;margin-top: 100px;"><img data-src="img01.png" width="100px" height="100px" style="margin-top: 1px;" class="lazyLoad"/></div><div style="width: 100px;height: 100px;margin-top: 300px;"><img data-src="img01.png" width="100px" height="100px" style="margin-top: 1px;" class="lazyLoad"/></div><div style="width: 100px;height: 100px;margin-top: 300px;"><img data-src="img01.png" width="100px" height="100px" style="margin-top: 1px;" class="lazyLoad"/></div><div style="width: 100px;height: 100px;margin-top: 300px;"><img data-src="img01.png" width="100px" height="100px" style="margin-top: 1px;" class="lazyLoad"/></div><script type="text/javascript">var imgArray=document.getElementsByClassName("lazyLoad");var len=imgArray.length;for (var i = 0; i < len; i++) {var oHeight=imgArray[i].offsetTop;//可视区域var height=document.documentElement.clientHeight;if (oHeight<height) {imgArray[i].src=imgArray[i].getAttribute("data-src");}}window.onscroll=function(){for (var i = 0; i < len; i++) {var oHeight=imgArray[i].offsetTop;//可视区域var height=document.documentElement.clientHeight;//滚动条距离顶部高度var scrollTop=document.documentElement.scrollTop||document.body.scrollTop;if (height+scrollTop>oHeight) {if (imgArray[i].src=="") {imgArray[i].src=imgArray[i].getAttribute("data-src");}}}};</script></body></html>


原创粉丝点击