JS图片懒加载
2021-05-11 本文已影响0人
爱学习的新一
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>图片懒加载</title>
</head>
<style type="text/css">
.imglist {
width: 300px;
display: flex;
flex-wrap: wrap;
text-align: center;
}
.lazy {
width: 280px;
height: 280px;
}
</style>
<body>
<div class="imglist">
<img class="lazy" src="img/loading.gif" data-src="img/01.png" alt="pic">
<img class="lazy" src="img/loading.gif" data-src="img/02.png" alt="pic">
<img class="lazy" src="img/loading.gif" data-src="img/03.png" alt="pic">
<img class="lazy" src="img/loading.gif" data-src="img/04.png" alt="pic">
<img class="lazy" src="img/loading.gif" data-src="img/05.png" alt="pic">
<img class="lazy" src="img/loading.gif" data-src="img/06.png" alt="pic">
<img class="lazy" src="img/loading.gif" data-src="img/07.png" alt="pic">
<img class="lazy" src="img/loading.gif" data-src="img/08.png" alt="pic">
<img class="lazy" src="img/loading.gif" data-src="img/09.png" alt="pic">
<img class="lazy" src="img/loading.gif" data-src="img/10.png" alt="pic">
<img class="lazy" src="img/loading.gif" data-src="img/11.png" alt="pic">
<img class="lazy" src="img/loading.gif" data-src="img/12.png" alt="pic">
<img class="lazy" src="img/loading.gif" data-src="img/13.png" alt="pic">
<img class="lazy" src="img/loading.gif" data-src="img/14.png" alt="pic">
<img class="lazy" src="img/loading.gif" data-src="img/15.png" alt="pic">
<img class="lazy" src="img/loading.gif" data-src="img/16.png" alt="pic">
<img class="lazy" src="img/loading.gif" data-src="img/17.png" alt="pic">
<img class="lazy" src="img/loading.gif" data-src="img/18.png" alt="pic">
</div>
</body>
<script type="text/javascript">
// onload是等所有的资源文件加载完毕以后再绑定事件
window.onload = function() {
// 获取图片列表,即img标签列表
var imgs = document.querySelectorAll('img');
// 获取到浏览器顶部的距离
function getTop(e) {
return e.offsetTop;
}
// 懒加载实现
function lazyload(imgs) {
// 可视区域高度
var h = window.innerHeight;
//滚动区域高度
var s = document.documentElement.scrollTop || document.body.scrollTop;
for (var i = 0; i < imgs.length; i++) {
//图片距离顶部的距离大于可视区域和滚动区域之和时懒加载
if ((h + s) > getTop(imgs[i])) {
// 真实情况是页面开始有2秒空白,所以使用setTimeout定时2s
(function(i) {
setTimeout(function() {
// 不加立即执行函数i会等于9
// 隐形加载图片或其他资源,
//创建一个临时图片,这个图片在内存中不会到页面上去。实现隐形加载
var temp = new Image();
temp.src = imgs[i].getAttribute('data-src'); //只会请求一次
// onload判断图片加载完毕,真是图片加载完毕,再赋值给dom节点
temp.onload = function() {
// 获取自定义属性data-src,用真图片替换假图片
imgs[i].src = imgs[i].getAttribute('data-src')
}
}, 2000)
})(i)
}
}
}
lazyload(imgs);
// 滚屏函数
window.onscroll = function() {
lazyload(imgs);
}
}
</script>
</html>
参考:'https://blog.csdn.net/w1418899532/article/details/90515969'