Intersection Observer API 是浏览器原生提供的,用于异步检测目标元素与视口或父元素是否产生交叉。它的优势在于提高性能和简化代码实现。

let observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
observer.unobserve(img);
}
});
}, {
root: null,
rootMargin: "0px",
threshold: 0.1
});

document.querySelectorAll('img').forEach(img => observer.observe(img));

posted @ 2024-05-29 16:50  jialiangzai  阅读(61)  评论(0)    收藏  举报