포시코딩

[IntersectionObserver] 무한 스크롤 (Infinite scroll) 본문

JavaScript

[IntersectionObserver] 무한 스크롤 (Infinite scroll)

포시 2023. 1. 24. 18:36
728x90

https://github.com/10-10-gaza/wonbin

 

GitHub - 10-10-gaza/wonbin

Contribute to 10-10-gaza/wonbin development by creating an account on GitHub.

github.com

 

https://eunoia07.tistory.com/entry/%EB%AC%B4%ED%95%9C-%EC%8A%A4%ED%81%AC%EB%A1%A4Infinite-scroll-%EA%B5%AC%ED%98%84%ED%95%98%EA%B8%B0?category=900349 

 

[JS] vanilla js로 무한 스크롤(Infinite scroll) 구현하기

🤔무한 스크롤(Infinite scroll)이란? 무한 스크롤은 사용자가 페이지 하단에 도달했을 때, 콘텐츠가 계속 로드되는 사용자 경험(UX) 방식입니다. 한 페이지 아래로 스크롤 하면 끝없이 새로운 화면

eunoia07.tistory.com

 

위 내용 참고해서 구현한 코드

window.onload = () => {
  infiniteScroll();
};

let page = 1;
let isGetOrdersWaitingLoading = false;

const infiniteScroll = () => {
  const scrollEnd = document.querySelector('#scroll-end');

  const io = new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
      if (!entry.isIntersecting) return;  
      // entry가 interscting 중이 아니라면 함수를 실행하지 않음
      if (isGetOrdersWaitingLoading) return;
      // 현재 page가 불러오는 중임을 나타내는 flag를 통해 불러오는 중이면 함수를 실행하지 않음

      observer.observe(scrollEnd);
      getOrdersWaiting(page);
      page += 1;
    });
  });
  io.observe(scrollEnd);
};

const getOrdersWaiting = (p) => {
  isGetOrdersWaitingLoading = true;
  
  console.log('p: ' + p);
  fetch('/api/orders?p='+p, {
    method: 'GET',
  })
    .then(async (res) => {
      // ...생략
    })
    .finally(() => {
      isGetOrdersWaitingLoading = false;
    });
};

 

728x90