IntersectionObserve
2024年06月18日
一、认识
二、实现
- javaScript
- html
- css
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);
});
<div class="box">
<img
src=""
class="lazy-load-img"
data-src="https://bolawen.github.io/resource/image/blog/10.png"
/>
<img
src=""
class="lazy-load-img"
data-src="https://bolawen.github.io/resource/image/blog/11.png"
/>
<img
src=""
class="lazy-load-img"
data-src="https://bolawen.github.io/resource/image/blog/12.png"
/>
<img
src=""
class="lazy-load-img"
data-src="https://bolawen.github.io/resource/image/blog/13.png"
/>
<img
src=""
class="lazy-load-img"
data-src="https://bolawen.github.io/resource/image/blog/14.png"
/>
<img
src=""
class="lazy-load-img"
data-src="https://bolawen.github.io/resource/image/blog/15.png"
/>
<img
src=""
class="lazy-load-img"
data-src="https://bolawen.github.io/resource/image/blog/16.png"
/>
<img
src=""
class="lazy-load-img"
data-src="https://bolawen.github.io/resource/image/blog/17.png"
/>
<img
src=""
class="lazy-load-img"
data-src="https://bolawen.github.io/resource/image/blog/18.png"
/>
<img
src=""
class="lazy-load-img"
data-src="https://bolawen.github.io/resource/image/blog/19.png"
/>
<img
src=""
class="lazy-load-img"
data-src="https://bolawen.github.io/resource/image/blog/20.png"
/>
<img
src=""
class="lazy-load-img"
data-src="https://bolawen.github.io/resource/image/blog/21.png"
/>
<img
src=""
class="lazy-load-img"
data-src="https://bolawen.github.io/resource/image/blog/22.png"
/>
<img
src=""
class="lazy-load-img"
data-src="https://bolawen.github.io/resource/image/blog/23.png"
/>
<img
src=""
class="lazy-load-img"
data-src="https://bolawen.github.io/resource/image/blog/24.png"
/>
<img
src=""
class="lazy-load-img"
data-src="https://bolawen.github.io/resource/image/blog/25.png"
/>
<img
src=""
class="lazy-load-img"
data-src="https://bolawen.github.io/resource/image/blog/26.png"
/>
<img
src=""
class="lazy-load-img"
data-src="https://bolawen.github.io/resource/image/blog/27.png"
/>
<img
src=""
class="lazy-load-img"
data-src="https://bolawen.github.io/resource/image/blog/28.png"
/>
<img
src=""
class="lazy-load-img"
data-src="https://bolawen.github.io/resource/image/blog/29.png"
/>
<img
src=""
class="lazy-load-img"
data-src="https://bolawen.github.io/resource/image/blog/30.png"
/>
</div>
.box {
width: 100%;
}
.box img {
display: block;
width: 400px;
height: 400px;
object-fit: cover;
}