웹 애플리케이션에서 무한 스크롤을 구현하는 방법

웹 애플리케이션에서 무한 스크롤을 구현하는 방법
당신과 같은 독자들이 MUO를 지원하는 데 도움을 줍니다. 귀하가 당사 사이트의 링크를 사용하여 구매하면 당사는 제휴 수수료를 받을 수 있습니다. 자세히 읽어보세요.

무한 스크롤을 사용하면 기존 페이지 매김의 클릭하여 로드 방식과 달리 사용자가 페이지를 아래로 이동할 때 콘텐츠가 계속 로드됩니다. 이 기능은 특히 모바일 장치에서 더욱 원활한 환경을 제공할 수 있습니다.





MUO 오늘의 영상 콘텐츠를 계속하려면 스크롤하세요.

일반 HTML, CSS 및 JavaScript를 사용하여 무한 스크롤을 설정하는 방법을 알아보세요.





프런트엔드 설정

콘텐츠를 표시하려면 기본 HTML 구조로 시작하세요. 예는 다음과 같습니다.





 <!DOCTYPE html> 
<html>
<head>
    <link rel="stylesheet" href="style.css" />
</head>
<body>
    <h1>Infinite Scroll Page</h1>

    <div class="products__list">
      <img src="https://fakestoreapi.com/img/71li-ujtlUL._AC_UX679_.jpg"
           alt="Jacket" />

      <img src="https://fakestoreapi.com/img/71li-ujtlUL._AC_UX679_.jpg"
           alt="Jacket" />

      <img src="https://fakestoreapi.com/img/71li-ujtlUL._AC_UX679_.jpg"
           alt="Jacket" />

      <img src="https://fakestoreapi.com/img/71li-ujtlUL._AC_UX679_.jpg"
           alt="Jacket" />

      <img src="https://fakestoreapi.com/img/71li-ujtlUL._AC_UX679_.jpg"
           alt="Jacket" />

      <img src="https://fakestoreapi.com/img/71li-ujtlUL._AC_UX679_.jpg"
           alt="Jacket" />
    </div>

    <script src="script.js"></script>
</body>
</html>

이 페이지에는 일련의 자리 표시자 이미지가 포함되어 있으며 CSS 파일과 JavaScript 파일이라는 두 가지 리소스를 참조합니다.

스크롤 가능한 콘텐츠에 대한 CSS 스타일링

자리 표시자 이미지를 그리드에 표시하려면 다음 CSS를 스타일.css 파일:



 * { 
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html { font-size: 62.5%; }

body {
  font-family: Cambria, Times, "Times New Roman", serif;
}

h1 {
  text-align: center;
  font-size: 5rem;
  padding: 2rem;
}

img {
  width: 100%;
  display: block;
}

.products__list {
  display: flex;
  flex-wrap: wrap;
  gap: 2rem;
  justify-content: center;
}

.products__list > * {
  width: calc(33% - 2rem);
}

.loading-indicator {
  display: none;
  position: absolute;
  bottom: 30px;
  left: 50%;
  background: #333;
  padding: 1rem 2rem;
  color: #fff;
  border-radius: 10px;
  transform: translateX(-50%);
}

현재 페이지는 다음과 같아야 합니다.

  HTML과 CSS를 추가한 후의 초기 페이지

JS를 사용한 핵심 구현

편집하다 script.js . 무한 스크롤을 구현하려면 사용자가 콘텐츠 컨테이너 또는 페이지 하단 근처에서 스크롤한 시기를 감지해야 합니다.





 "use strict"; 

window.addEventListener("scroll", () => {
  if (
    window.scrollY + window.innerHeight >=
      document.documentElement.scrollHeight - 100
  ) {
    // User is near the bottom, fetch more content
    fetchMoreContent();
  }
});

그런 다음 더 많은 자리 표시자 데이터를 가져오는 함수를 만듭니다.

 async function fetchMoreContent() { 
  try {
    let response = await fetch("https://fakestoreapi.com/products?limit=3");

    if (!response.ok) {
      throw new Error("Network response was not ok");
    }

    let data = await response.json();
    console.log(data);
  } catch (error) {
    console.error("There was a problem fetching new content:", error);
  } finally {
    console.log("Fetch function fired");
  }
}

이 프로젝트에서는 다음의 API를 사용할 수 있습니다. fakestoreapi .





스크롤 시 데이터를 가져오는 중인지 확인하려면 콘솔을 살펴보세요.

  스크롤 시 가져오기 함수가 호출되었는지 확인

스크롤 시 데이터를 여러 번 가져오는 것을 볼 수 있으며 이는 장치 성능을 저하시키는 요인이 될 수 있습니다. 이를 방지하려면 데이터의 초기 가져오기 상태를 만듭니다.

 let isFetching = false; 

그런 다음 이전 가져오기가 완료된 후에만 데이터를 가져오도록 가져오기 함수를 수정하세요.

윈도우 서버 2016 대 윈도우 10
 async function fetchMoreContent() { 
  if (isFetching) return; // Exit if already fetching

  isFetching = true; // Set the flag to true

  try {
    let response = await fetch("https://fakestoreapi.com/products?limit=3");

    if (!response.ok) {
      throw new Error("Network response was not ok");
    }

    let data = await response.json();
  } catch (error) {
    console.error("There was a problem fetching new content:", error);
  } finally {
    console.log("Fetch function fired");
    isFetching = false; // Reset the flag to false
  }
}

새 콘텐츠 표시

사용자가 페이지를 아래로 스크롤할 때 새 콘텐츠를 표시하려면 상위 컨테이너에 이미지를 추가하는 함수를 만듭니다.

먼저 상위 요소를 선택합니다.

 const productsList = document.querySelector(".products__list"); 

그런 다음 콘텐츠를 추가하는 함수를 만듭니다.

 function displayNewContent(data) { 
  data.forEach((item) => {
    const imgElement = document.createElement("img");
    imgElement.src = item.image;
    imgElement.alt = item.title;
    productsList.appendChild(imgElement); // Append to productsList container
  });
}

마지막으로 가져오기 함수를 수정하고 가져온 데이터를 추가 함수에 전달합니다.

 async function fetchMoreContent() { 
  if (isFetching) return;

  isFetching = true;

  try {
    let response = await fetch("https://fakestoreapi.com/products?limit=3");

    if (!response.ok) {
      throw new Error("Network response was not ok");
    }

    let data = await response.json();
    displayNewContent(data);
  } catch (error) {
    console.error("There was a problem fetching new content:", error);
  } finally {
    console.log("Fetch function fired");
    isFetching = false;
  }
}

이제 무한 스크롤이 작동합니다.

  무한 스크롤 작동

무한 스크롤 향상

사용자 경험을 향상시키기 위해 새 콘텐츠를 가져올 때 로딩 표시기를 표시할 수 있습니다. 이 HTML을 추가하여 시작하세요.

 <h1 class="loading-indicator">Loading...</h1> 

그런 다음 로딩 요소를 선택합니다.

 const loadingIndicator = document.querySelector(".loading-indicator"); 

마지막으로 로딩 표시기의 가시성을 전환하는 두 가지 함수를 만듭니다.

 function showLoadingIndicator() { 
  loadingIndicator.style.display = "block";
  console.log("Loading...");
}

function hideLoadingIndicator() {
  loadingIndicator.style.display = "none";
  console.log("Finished loading.");
}

그런 다음 가져오기 기능에 추가하세요.

 async function fetchMoreContent() { 
  if (isFetching) return; // Exit if already fetching

  isFetching = true;
  showLoadingIndicator(); // Show loader

  try {
    let response = await fetch("https://fakestoreapi.com/products?limit=3");

    if (!response.ok) {
      throw new Error("Network response was not ok");
    }

    let data = await response.json();
    displayNewContent(data);
  } catch (error) {
    console.error("There was a problem fetching new content:", error);
  } finally {
    console.log("Fetch function fired");
    hideLoadingIndicator(); // Hide loader
    isFetching = false;
 }
}

다음을 제공합니다.

무한 스크롤에 대한 모범 사례

따라야 할 몇 가지 모범 사례는 다음과 같습니다.

  • 동시에 너무 많은 항목을 가져오지 마십시오. 이는 브라우저에 부담을 주고 성능을 저하시킬 수 있습니다.
  • 스크롤 이벤트 감지 즉시 콘텐츠를 가져오는 대신, 디바운스 기능을 사용하세요 가져오기를 약간 지연시킵니다. 이것은 할 수 있다 과도한 네트워크 요청 방지 .
  • 모든 사용자가 무한 스크롤을 선호하는 것은 아닙니다. 다음과 같은 옵션을 제공합니다. 페이지 매김 구성 요소 사용 만약 원한다면.
  • 더 이상 로드할 콘텐츠가 없으면 계속해서 더 많은 콘텐츠를 가져오려고 시도하는 대신 사용자에게 알립니다.

원활한 콘텐츠 로딩 마스터하기

무한 스크롤을 사용하면 사용자가 콘텐츠를 원활하게 탐색할 수 있으며 모바일 장치를 사용하는 사람들에게 좋습니다. 이 기사의 팁과 중요한 조언을 활용하면 웹사이트에 이 기능을 추가할 수 있습니다.

사용자가 사이트를 사용할 때 어떻게 느끼는지 생각해 보세요. 사용자가 무슨 일이 일어나고 있는지 알 수 있도록 진행 표시 및 오류 메모 등을 표시합니다.