通过 IntersectionObserver api 来实现图片懒加载的功能
代码如下
// 遍历所有具有data-src属性的图片,并将其添加到IntersectionObserver中
const images = document.querySelectorAll('img[data-src]');
const options = {
root: null, // 使用viewport作为root
rootMargin: '0px',
threshold: 0.1 // 设置交叉比例
};
// 创建IntersectionObserver实例
const observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
const src = img.getAttribute('data-src');
// 加载图像
img.setAttribute('src', src);
// 图像加载后,不再需要IntersectionObserver来观察该图像
observer.unobserve(img);
}
});
}, options);
// 将图片添加到IntersectionObserver观察列表
images.forEach(image => {
observer.observe(image);
});