
IntersectionObserver 은 JS의 Web API 중 하나로, 브라우저에서 기본으로 제공하는 표준 내장 객체이다
scroll 위치에 따라 어떤 요소가 viewport 안에 들어왔는지 자동 감지한다
이는 DOM 요소와 viewport 간의 교차 상태를 비동기로 추적한다
활용예시
- 사용자가 scroll로 특정 섹션에 도달했는지 감지
- lazy loading 이미지 처리
- 특정 요소 화면 진입 시 애니메이션 발동
const observer = new IntersectionObserver(callback, options)
observer.observe(targetElement)
타겟 요소가 뷰포트에 들어오거나 나갈때 자동으로 호출
(entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
console.log("요소가 보임")
}
})
}
옵저버의 동작 방식을 설정하는 옵션 객체
{
root : null, // 기준 요소 (null 이면 뷰포트)
rooMargin: "0px", // 기준 요소에서 얼마나 margin을 둘지
threshold: 0.5 // 0~1 사이의 값 (0.5 이면 50% 이상 보여야 감지)
}
observer.observe(targetElement) //감지 시작
observer.unobserve(targetElement) // 감지 중단
const callback = (entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) console.log("보임", entry.target)
else console.log("안보임", entry.target)
})
}
const options = {
threshold: 0.5
}
const observer = new Intersection(callback, options)
const section = document.querySelector("#section")
observer.observe(section)
IntersectionObserver 는 scroll 이벤트 없이도 요소의 노출 여부를 감지할 수 있기 때문에 성능이 좋고 효율적인 방법이다