跳到主要内容

IntersectionObserve

2024年06月18日
柏拉文
越努力,越幸运

一、认识


二、实现


const lazyLoadImgList = document.querySelectorAll(".lazy-load-img");
const intersectionObserverOption = {
threshold: 0,
};

function loadImg(imgDom) {
const src = imgDom.getAttribute("data-src");
imgDom.src = src;
}

function intersectionObserverCallback(entries, observer) {
entries.forEach((entry) => {
if (entry.isIntersecting) {
observer.unobserve(entry.target);
loadImg(entry.target);
}
});
}

const intersectionObserver = new IntersectionObserver(
intersectionObserverCallback,
intersectionObserverOption
);
lazyLoadImgList.forEach((lazyLoadImg) => {
intersectionObserver.observe(lazyLoadImg);
});