
오늘은 사용자가 스크롤을 내릴 때마다 추가 상품이 자동으로 로드되는 무한 스크롤 기능을 완성했습니다. 단순한 페이지네이션을 넘어서 끊임없는 사용자 경험을 제공하는 모던 웹 애플리케이션의 핵심 기능을 구현했습니다.
// 무한 스크롤을 위한 상태 변수들
let currentPage = 1;
let currentLimit = 20;
let currentSort = "price_asc";
let isLoading = false;
let hasMoreProducts = true;
export async function updateCardProducts(limit, sort) {
// 상태 초기화
currentPage = 1;
currentLimit = limit;
currentSort = sort;
hasMoreProducts = true;
// 로딩 상태 표시 후 데이터 로드
}
export async function loadMoreProducts() {
if (!hasMoreProducts || isLoading) return;
currentPage += 1;
// 로딩 스켈레톤 추가
productsGrid.insertAdjacentHTML("beforeend", createLoadingSkeleton(4));
// 새로운 상품 데이터 로드 후 기존 목록에 추가
}
// ❌ innerHTML: 기존 DOM 요소들을 모두 삭제 후 재생성
productsGrid.innerHTML += newHTML; // 이벤트 리스너 소실!
// ✅ insertAdjacentHTML: 기존 요소 유지하며 새 요소만 추가
productsGrid.insertAdjacentHTML("beforeend", newHTML); // 이벤트 리스너 보존!
깨달은 점:
// 상품 로드 가능 여부 판단 로직
if ((currentPage - 1) * currentLimit + newProducts.length >= total) {
hasMoreProducts = false;
}
import { loadMoreProducts } from "../componets/updateProductsCard.js";
export function setupInfiniteScroll() {
window.addEventListener("scroll", () => {
// 페이지 하단에 도달했는지 확인
const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
const windowHeight = window.innerHeight;
const documentHeight = document.documentElement.offsetHeight;
// 하단 200px 전에 미리 로드
if (scrollTop + windowHeight >= documentHeight - 200) {
loadMoreProducts();
}
});
}