一张图片就是一个标签,而图片的来源主要是src属性。浏览器是否发起请求就是根据是否有src属性决定的。
那么我们就要对标签的src属性下手了,在没进入可视区域的时候,我们先不给这个标签赋src属性,这样浏览器就不会发送请求了。
总结:我们知道了从标签下手,那么更重要的就是可视区域的判断了
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>图片懒加载</title>
<style>
img {
display: block;
width: 100%;
height: 300px;
margin-bottom: 20px;
}
</style>
</head>
<body>
<img class="lazy-img" data-src="./images/1.jpg" alt="">
<img class="lazy-img" data-src="./images/2.jpg" alt="">
<img class="lazy-img" data-src="./images/3.jpg" alt="">
<img class="lazy-img" data-src="./images/4.jpg" alt="">
<img class="lazy-img" data-src="./images/5.jpg" alt="">
<img class="lazy-img" data-src="./images/6.jpg" alt="">
<img class="lazy-img" data-src="./images/7.jpg" alt="">
<img class="lazy-img" data-src="./images/8.jpg" alt="">
<img class="lazy-img" data-src="./images/9.jpg" alt="">
<img class="lazy-img" data-src="./images/10.jpg" alt="">
<img class="lazy-img" data-src="./images/1.jpg" alt="">
<img class="lazy-img" data-src="./images/2.jpg" alt="">
</body>
<script type="text/javascript">
new Vue ({
el: "vueBox",
data: {
},
methods: {
//用来判断bound.top<=clientHeight的函数,返回一个bool值
isInArea(el) {
let bound = el.getBoundingClientRect();
let clientHeight = window.innerHeight;
return bound.top <= clientHeight;
},
//检查图片是否在可视区内,如果不在,则加载
checkVisible(imgs) {
let vm = this;
Array.from(imgs).forEach(function(value) {
if (vm.isInArea(value)) {
vm.loadImg(value);
}
});
},
loadImg(el) {
if (!el.src) {
let source = el.dataset.src;
el.src = source;
}
},
loadData() {
let vm = this;
let i = 1;
let selectors = document.getElementsByClassName('lazy-img');
vm.checkVisible(selectors);
//throttle是一个节流函数
$('.wrap-con').scroll(throttle(function() {
vm.checkVisible(selectors);
}));
},
},
mounted: function () {
this.loadData();
},
});
</script>
</html>