[sample coding] js infininte scroll loading

SeoYng·2022년 1월 24일
0
post-thumbnail

요즘은 페이지네이션들이 대부분 인피니트 로드(무한 스크롤) 방식으로 구현되어있다. 이를 간단히 구현해보자

👀 인피니트 로드(무한 스크롤) 방식
-> 스크롤하여 화면 최하단으로 도달시 다음 list fetch하여 아이템 불러옴

📃.js


let NxtPageNum = 2; // 호출 페이지 넘버
let isLastPage = false; // 마지막페이지인지 여부
let isPending = false; // 로딩중 여부
const SUPPL_PX = 3; // 안드로이드 scroll bottom 소숫점 위한 보간

// item 호출 api
const fetchList = () => { 
  //.. fetch API
}

// 다음 item reFetch
const $_fetchNextItems = () => {
  isPending = true;
  const payload = { pageNumber: NxtPageNum };
  fetchList(payload).then(isLastPage => {
    if(!isLastPage) {
      NxtPageNum++;
    } else {
      isLastPage = true
    }
    isPending = false;
  });
},
      
const $_handleScroll = () => {
  // scroll bottom check
  const curScroll = window.innerHeight + window.scrollY + SUPPL_PX;
  const isBottom = curScroll >= document.body.scrollHeight;
  if (isLastPage && !isPending && isBottom) {
    $_fetchNextExpacts();
  }
},
      
/* 이벤트 등록 */
window.addEventListener('scroll', $_handleScroll);
/* 이벤트 해제 */
// window.removeEventListener('scroll', $_handleScroll);  

      
profile
Junior Web FE Developer

0개의 댓글