여러이미지나 다중이미지 또는 영상을 사용할경우, 스크롤에 따라 감지하는 방법은 너무나도 원초적인 방법이라 오히려 최적화된 화면구현에 방해가 될 수 있다.
이럴때 사용하는 것이 바로IntersectionObserver
라는 기능이다.
IntersectionObserver
는 뷰포트 화면 사이의 intersection
내의 변화를 비동기
적으로 관찰하는 방법이며, 이 방법을 통해 해당 구간에 도달하였을때 내가 원하는 이벤트 실행을 실행시키는것이 가능하다!
스크롤여부에 따라 데이터를 사용하기 때문에 최적화된 환경을 만들수 있다.
(인터넷 익스플로러 환경에서는 제공되지 않음)
https://developer.mozilla.org/ko/docs/Web/API/Intersection_Observer_API
let options = {
root: document.querySelector('#scrollArea'), //대상 객체
rootMargin: '0px', //root 가 가진 여백
threshold: 1.0 // 만일 50%만큼 요소가 보여졌을 때를 탐지하고 싶다면, 값을 0.5로 설정
}
let observer = new IntersectionObserver(callback, options); //콜백함수 설정!(필수)
intersection observer를 생성하기 위해서는 생성자 호출 시 콜백 함수를 제공해야 합니다. 이 콜백 함수는 threshold가 한 방향 혹은 다른 방향으로 교차할 때 실행됩니다.
=> 나머지 설정은 Docs 활용하기
import React, { useEffect, useRef } from 'react'
function Card(props) {
const imgRef = useRef(null) //dom 요소에 접근할때 useRef 사용
useEffect(()=>{
const options = {};
const callback = (entries,observer) => {
entries.forEach(entry =>{
if(entry.isIntersecting){ //이미지가 보이는 순간에만 로드되도록 하고싶은 경우
entry.target.src = entry.target.dataset.src;
//data-src요소를 src에 담기
observer.unobserve(entry.target)
//옵저버 이벤트가 실행됐으면 다시 이미지가 호출되지 않도록 할 수 있다. (최초실행)
}
})
}
const observer = new IntersectionObserver(callback,options)
observer.observe(imgRef.current);
},[]) //최초 한번만 실행
return (
<div className="Card text-center">
<img data-src={props.image} ref={imgRef}/>
<div className="p-5 font-semibold text-gray-700 text-xl md:text-lg lg:text-xl keep-all">
{props.children}
</div>
</div>
)
}
export default Card
활용할 수 있는 entries 이벤트 요소는 이렇게 있다.