[Intersection Observer API]무한 스크롤을 만들어보자

maru5mango·2022년 4월 9일
0

example

<div id="parent">
   <div id="id"></div>
</div>
  • js
const options = { threshold: 1.0 };
const callback = (entries, observer) => {
    entries.forEach((entry) => {
        if (entry.isIntersecting) {
            observer.unobserve(entry.target);
            getAPI();
            console.log('화면에서 노출됨');
        } else {
            console.log('화면에서 제외됨');
        }
    });
}
const observer = new IntersectionObserver(callback, options);
observer.observe(
    document.getElementById('id')
);


let isLast = false;
function getAPI(){
  if(isLast) return;
  const $parent = document.getElementById("parent");
  const $child = document.createElement('div');
  $child.classList.add('item');
  document.getElementById('id').setAttribute('id', '');
  for (let i =0; i<10; i++) {
    const $el = $child.cloneNode()
    if(Array.from($parent.children).length > 45) {
      isLast = true;
      break;
    }
    if(i===9){
      $el.setAttribute('id', 'id');
      observer.observe($el);
    }
    $el.innerHTML = Array.from($parent.children).length;
    $parent.append($el);
  };
}

Intersection Observer API는 관측하는 Target Element가 viewPort에 교차하는 순간을 감지하는 API입니다.
그러니까 Target으로 지정한 Element가 지금 화면에 보이는지 여부를 판단할 수 있습니다.

어떻게 사용할까?

// Observer 옵션
const options = {
  root: document.querySelector('#scrollArea'),
  rootMargin: '0px',
  threshold: 1.0
}

// 타겟 Viewport에서의 변화 감지 -> 화면에 보이거나, 사라질 때 실행될 함수
const callback = (entries, observer) => {
  entries.forEach(entry => {
    // target element:
    //   entry.boundingClientRect
    //   entry.intersectionRatio
    //   entry.intersectionRect
    //   entry.isIntersecting
    //   entry.rootBounds
    //   entry.target
    //   entry.time
  });
};

// Observer 선언
const observer = new IntersectionObserver(callback, options);

// 타겟 요소 관측 시작
observer.observe(TargetElement);

// 타겟 요소 관측 중단
observer.unobserve(TargetElement);

// 모든 요소 관측 중단
observer.disconnect();

// 관측 중인 모든 요소를 배열 형태로 반환
observer.takeRecords();
  • option은 root, rootMargin, threshold를 조절할 수 있습니다.
    • root를 지정하지 않으면 기본적으로 브라우저 뷰포트로 설정됩니다.
    • rootMargin은 root의 boundingBox를 수축하거나 증가시킵니다.
    • threshold는 targetElement가 얼마나 보일 때 콜백을 실행 시킬지를 결정합니다.

참고자료

https://developer.mozilla.org/ko/docs/Web/API/Intersection_Observer_API

0개의 댓글