104-图片懒加载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
let imgList = document.querySelectorAll('img'); // 获取页面中所有img对象

let observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.intersectionRatio > 0 && entry.intersectionRatio <= 1) {
// intersectionRatio 表示相交区域和目标元素的比例值
// 也可以用sIntersecting 目标元素当前是否可见 Boolean值 可见为true
entry.target.src = entry.target.dataset.src
// 图片进入进入可见区域, 则赋予data-src值给src属性
observer.unobserve(entry.target)
// 图片已加载, 解除观察
}
})
})
imgList.forEach(img => {
observer.observe(img); // 观察每一个图片对象
})