javascript

IntersectionObserver 이용한 인피니티 스크롤 예제

hjcode 2020. 4. 3. 16:48

IntersectionObserver는 대상 요소와 뷰포트의 교차 영역에 대한 변화를 비동기적으로 감지하도록 도와줍니다.

비동기로 실행되기 때문에 scroll 이벤트 요소에서 발생하는 이벤트가 연속으로 호출되는 문제가 없습니다.

 

const io = new IntersectionObserver(callback, options) 
io.observe(element) // 대상 요소 감시 시작

 

const io = new IntersectionObserver(entries => {
	if (entries[0].intersectionRatio <= 0) return;
	console.log('Loaded new items');
});

io.observe(document.querySelector('.target')); // 관찰 시작

entries는 다음의 속성들이 있습니다.

 

  • boundingCliendRect: 타겟의 정보
  • intersectionRect: 타겟의 교차 영역 정보
  • intersectionRatio: 타겟의 교차한 영역 비율(Number)
  • isIntersecting: 타겟의 교차 상태(Boolean)
  • rootBounds: 루트 요소의 정보
  • target: 타겟 요소
  • time: 변경 발생 시간

예제

const ele = document.querySelector('.scroll');

const io = new IntersectionObserver(entries => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      add();
    }
  });
});
io.observe(ele);

function add() {
	const $div = document.createElement("div");
	ele.before($div)
}

jsfiddle에서 보기

https://jsfiddle.net/hyuckjin/3yswdjrb/

 

Intersection Observer infiniteScroll - JSFiddle - Code Playground

 

jsfiddle.net

IE도 지원이 되도록 하는 라이브러리도 있습니다.

https://www.npmjs.com/package/intersection-observer

 

intersection-observer

A polyfill for IntersectionObserver

www.npmjs.com

References

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

 

IntersectionObserver

viewport

developer.mozilla.org

 

반응형