图片懒加载是一种节省性能的图片加载方法。通过判断图片是否进入可视区来控制它是否加载。具体的实现逻辑如下
以下是html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="window">
<img data-src="./static/pic1.jpg" src="./static/pic0.jpg" alt="">
<img data-src="./static/pic2.jpg" src="./static/pic0.jpg" alt="">
<img data-src="./static/pic3.jpg" src="./static/pic0.jpg" alt="">
<img data-src="./static/pic4.jpg" src="./static/pic0.jpg" alt="">
<img data-src="./static/pic5.jpg" src="./static/pic0.jpg" alt="">
<img data-src="./static/pic6.jpg" src="./static/pic0.jpg" alt="">
<img data-src="./static/pic7.jpg" src="./static/pic0.jpg" alt="">
<img data-src="./static/pic8.jpg" src="./static/pic0.jpg" alt="">
<img data-src="./static/pic9.jpg" src="./static/pic0.jpg" alt="">
</div>
</body>
</html>
<style>
.window {
width: 500px;
height: 3500px;
margin: 0 auto;
overflow: hidden;
}
img {
width: 500px;
height: 400px;
}
</style>
我们为window.scroll做了防抖控制,这样能更好的提升性能。
js代码
let elements = document.querySelectorAll('img')
let arr = Array.from(elements)
window.onscroll = debounce(lazyLoad, 1000)
function debounce(fun, delay) {
let timer = null
return function () {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fun.call()
}, delay);
}
}
function lazyLoad() {
arr.forEach((ele, idx, arr) => {
//getBoundingClientRect.top 获取元素在窗口上的位置
//img元素的offsetParent是body,那么offsetTop就是图片到body顶部的距离
//offsetTop < scrollTop+clientHeight
//window.innerHeight 浏览器窗口的视口高度
console.log(ele.offsetParent, 'offsetParent')
console.log(ele.clientHeight, 'clientHeight')
console.log(document.documentElement.scrollTop, 'scrollTop')
console.log(ele.offsetTop, 'offsetTop')
console.log(window.innerHeight, 'window.innerHeight')
let top = ele.getBoundingClientRect().top
//以下两种方式都可以
// if (top <= window.innerHeight) {
if(ele.offsetTop < document.documentElement.scrollTop + window.innerHeight){
//ele.attributes
ele.setAttribute('src', ele.getAttribute('data-src'))
}
})
}