图片懒加载的几种方式

通过 img 标签

1
2
3
4
5
6
7
<div style={{ height: '300px', overflow: 'auto'}}>
{items.map(item => (
<div key={item.id}>
<img src={item.src} loading="lazy" decoding="async" />
</div>
))}
</div>

这里使用 react 来做实例,items 是一个图片数组,我们给 img 标签的 loading 属性设置 “lazy” 来开启懒加载。需要注意的是该属性在浏览器的兼容性

滚动上去的高度 + 浏览器可视区高度 >= 图片距离文档顶部的高度

1
2
3
4
5
6
7
8
<img data-src="img/1.jpg" src="img/0.png" alt="xxx" />
<img data-src="img/2.jpg" src="img/0.png" alt="xxx" />
<img data-src="img/3.jpg" src="img/0.png" alt="xxx" />
<img data-src="img/4.jpg" src="img/0.png" alt="xxx" />
<img data-src="img/5.jpg" src="img/0.png" alt="xxx" />
<img data-src="img/6.jpg" src="img/0.png" alt="xxx" />
<img data-src="img/7.jpg" src="img/0.png" alt="xxx" />
<img data-src="img/8.jpg" src="img/0.png" alt="xxx" />
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//获取全部img标签
var images = document.getElementsByTagName("img");

window.addEventListener("scroll", (e) => {
//当发生滚动事件时调用ergodic事件
ergodic();
});
function ergodic() {
// 遍历每一张图
for (let i of images) {
//判断当前图片是否在可视区内
if (i.offsetTop <= window.innerHeight + window.scrollY) {
//获取自定义data-src属性的值
let trueSrc = i.getAttribute("data-src");
//把值赋值给图片的src属性
i.setAttribute("src", trueSrc);
}
}
}
//没发生滚动事件时也要先执行一次
ergodic();

使用 Intersection Observer API

首先,在页面中将所有需要懒加载的图片的 src 属性设置为占位符或者一个小的loading图。

使用 Intersection Observer API 来监测图片元素是否进入了可视区域,并在图片进入可视区域时加载真实的图片。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!-- HTML -->
<img data-src="image.jpg" class="lazy-load" alt="Lazy-loaded image">

<!-- JavaScript -->
<script>
const lazyImages = document.querySelectorAll('.lazy-load');

const lazyLoad = target => {
const io = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
const src = img.getAttribute('data-src');

img.setAttribute('src', src);
observer.disconnect();
}
});
});

io.observe(target);
};

lazyImages.forEach(lazyLoad);
</script>

在这个示例中,我们首先将需要懒加载的图片的真实路径存储在 data-src 属性中,
并添加一个具有 lazy-load 类名的标记。然后使用 JavaScript 遍历所有具有 lazy-load 类名的图片元素,
对每个图片元素应用 Intersection Observer,一旦图片元素进入视口(即可见),就将 data-src 的值赋给 src 属性以加载真实的图片。


图片懒加载的几种方式
https://l1ushun.github.io/2022/12/21/lazy-image-loading/
作者
liu shun
发布于
2022年12月21日