Intersection Observer API

MINIBAIK·2022년 6월 20일
0

Web Technology

목록 보기
1/18


image ref: https://ji5485.github.io/post/2021-05-01/developing-infinite-scroll-using-intersection-observer-api/


Intersection Observer API


Intersection Observer API는 프론트단에서 특정 라이브러리 없이 무한 스크롤을 구현할 때 주로 사용한다. Intersection Observer API에 대해 알아보자.

MDN Docs에 따르면, Intersection Observer API는 2016년 4월 구글 개발자 페이지 통해 소개되고, 타겟 요소와 상위 요소 또는 최상위 document 의 viewport 사이의 intersection 내의 변화를 비동기적으로 관찰하는 방법이라고 한다.

쉽게 풀면 내가 지정한 타겟과 내가 현재 보고 있는 화면 또는 스크롤이 일치하는지를 지속적으로 관찰하고 있는 옵저버이다. 지정한 타겟과 화면(뷰포트)이 일치할 시에 특정 함수를 실행시킬 수 있고, margin 등을 지정할 수 있는 옵션을 제공해준다. 자바스크립트를 사용할 시에 내장되어 있어 특정 라이브러리를 찾아 붙히지 않아도 무한 스크롤 등을 구현할 수 있다.



Intersection Observer API의 주 사용처는 이렇고 한다.

  • 페이지가 스크롤 되는 도중에 발생하는 이미지나 다른 컨텐츠의 지연 로딩.
  • 스크롤 시에, 더 많은 컨텐츠가 로드 및 렌더링되어 사용자가 페이지를 이동하지 않아도 되게 하는 infinite-scroll 을 구현.
  • 광고 수익을 계산하기 위한 용도로 광고의 가시성 보고.
  • 사용자에게 결과가 표시되는 여부에 따라 작업이나 애니메이션을 수행할 지 여부를 결정.

Example


Docs에 나와있는 예시 코드는 이렇다.

let options = {
  root: document.querySelector('#scrollArea'),
  rootMargin: '0px',
  threshold: 1.0
}

let observer = new IntersectionObserver(callback, options);

IntersectionObserver 객체를 만들고 그 안에 콜백함수와 옵션을 주어 구현한다.
observer를 선언 후에는 타겟을 지정해주면 해당 위치를 옵저빙하게 된다.

let target = document.querySelector('#listItem');
observer.observe(target);


이를 응용하여 리액트에서는 custom hook으로 만들어 간편하게 사용할 수 있다.
파라미터로 받게 되는 target은 useRef를 이용하여 특정 DOM을 컨택하면 된다. callback 함수인 onIntersect를 이용하여 원하는 시점에 내가 원하는 함수를 지정하여 실행시키면 된다.


// hook

import { useEffect } from 'react'


const useIntersectionObserver = ({ root, target, onIntersect, threshold = 1.0, rootMargin = '0px' }) => {
    useEffect(() => {
        const observer = new IntersectionObserver(onIntersect, {
            root,
            rootMargin,
            threshold
        })
        
        if (!target) {
            return
        }
        
        observer.observe(target)
        
        return () => {
            observer.unobserve(target)
        }
    }, [target, root, rootMargin, onIntersect, threshold])
}

export default useIntersectionObserver

// view

const targetRef = useRef(null)
...
...
<div ref={targetRef}/>
profile
Organize theories during development.

0개의 댓글