컴포넌트 연습하기 - Text
컴포넌트 연습하기 - Header
컴포넌트 연습하기 - Image
컴포넌트 연습하기 - Spacer
컴포넌트 연습하기 - Spinner
컴포넌트 연습하기 - Toggle
Intersection Observer
Intersection Observer란 Target Element가 화면에 노출되었는지 여부를 간단하게 확인할 수 있게 구독할 수 있는 API이다.
MDN에서는 intersection Observer의 필요성을 다음과 같이 설명한다.
사용 예시 - Lazy loading
const options = {
root: null,
rootMargin: "0px 0px 30px 0px",
threshold: 0.5,
};
const io = new IntersectionObserver((entries, observer) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
console.log("0.5 화면 노출");
entry.target.src = entry.target.dataset.src;
observer.unobserve(entry.target);
}
});
}, options);
const images = document.querySelectorAll(".image");
images.forEach((el) => {
io.observe(el);
});
해당 과정을 설명하자면,
IntersectionObserver 객체를 생성하고 callback 함수와 option들을 전달한다.
구독할 대상을 선언하고 해당 target element를 구독한다.
options.threshold 만큼 화면에 노출되면 이미지를 로드한다.
이미지를 불러왔다면 target element에 대한 구독을 멈춘다.