train of thought
Put the real src of img in the custom attribute data-src, get the viewport and scroll bar height of the page, traverse the img, and assign a value to src if the offsetTop of img is in the visible area
renderings
the code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>手写懒加载</title>
<style>
img {
display: flex;
margin-bottom: 30px;
border-radius: 3px;
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<img src="./image/loading.gif" data-src="./image/Bootstrap.png" alt="">
<img src="./image/loading.gif" data-src="./image/Docker.png" alt="">
<img src="./image/loading.gif" data-src="./image/GitHub.png" alt="">
<img src="./image/loading.gif" data-src="./image/HTML5.png" alt="">
<img src="./image/loading.gif" data-src="./image/IDEA.png" alt="">
<img src="./image/loading.gif" data-src="./image/Java.png" alt="">
<img src="./image/loading.gif" data-src="./image/MySQL.png" alt="">
<img src="./image/loading.gif" data-src="./image/Redis.png" alt="">
<img src="./image/loading.gif" data-src="./image/Spring-Boot.png" alt="">
<img src="./image/loading.gif" data-src="./image/Spring.png" alt="">
<!-- 懒加载 -->
<script>
// 获取所有img元素
const img = document.querySelectorAll('img')
// 加载到了第几个了
let num = 0
lazyLoad()
window.onscroll = lazyLoad
// 懒加载
function lazyLoad() {
// 视口
let viewport = document.documentElement.clientHeight
// 滚动条
let scrollTop = document.documentElement.scrollTop || document.body.scrollTop
for (let i = num; i < img.length; i++) {
if (img[i].offsetTop < viewport + scrollTop) {
if (img[i].getAttribute('src') == './image/loading.gif') {
img[i].src = img[i].getAttribute('data-src')
}
num = i + 1
}
}
}
</script>
</body>
</html>