Appearance
html
<!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>Document</title>
<style>
html,
body {
height: 500%;
}
div {
width: 200px;
height: 200px;
background-color: #ddd;
margin: 0 auto;
margin-top: 1000px;
}
div img {
width: 100%;
height: 100%;
opacity: 0;
transition: opacity .3s;
/*
开始图片是隐藏的,在某些IE浏览器中,如果图片src是空的或者加载的图片是错误的,图片
不隐藏,会显示一个 X 的效果,很难看.
方法1: display: none => 加载真实图片后设置display: block会触发DOM的回流重绘.
性能消耗较大
方法2: opacity: 0 => 加载真实图片后设置opacity: 1不会引发DOM回流重绘,另一方面
还可以结合css3动画实现渐现效果.推荐.
*/
}
</style>
</head>
<body>
<div>
<img src="" alt="" data-img="./demo.png">
</div>
<div>
<img src="" alt="" data-img="./demo2.webp">
</div>
<div>
<img src="" alt="" data-img="./demo3.webp">
</div>
<script type="module">
import throttle from './throttle.js'
const containers = document.querySelectorAll('div')
const html = document.documentElement
function lazyLoading() {
for (let i = 0, l = containers.length; i < l; i++) {
const img = containers[i].querySelector('img')
const container = containers[i]
if (img.isLoaded) {
continue
}
let { bottom, top } = container.getBoundingClientRect()
// top >= 0实现了刷新时只加载在可视区内的图片
if (bottom <= html.clientHeight && top >= 0) {
img.src = img.getAttribute('data-img')
img.onload = () => {
// 图片加载成功
img.style.opacity = 1
img.isLoaded = true
img.removeAttribute('data-img')
}
}
}
}
window.addEventListener(
'scroll',
throttle(lazyLoading, 200, { trailing: true })
)
</script>
</body>
</html>