ESC

Type to search the knowledge base.

SnippetJavaScript

Infinite Scroll

Load more content when the sentinel enters the viewport via IntersectionObserver.

Explanation

Prefer IntersectionObserver over scroll math. Observe a sentinel at the list bottom; when visible, fetch the next page and disconnect while loading to avoid duplicates.

javascript
export function createInfiniteScroll({
  root = null,
  rootMargin = '200px',
  onLoadMore,
  hasMore,
}) {
  let loading = false;
  const sentinel = document.createElement('div');
  sentinel.setAttribute('aria-hidden', 'true');

  const io = new IntersectionObserver(
    async ([entry]) => {
      if (!entry.isIntersecting || loading || !hasMore()) return;
      loading = true;
      try {
        await onLoadMore();
      } finally {
        loading = false;
      }
    },
    { root, rootMargin }
  );

  return {
    sentinel,
    observe() { io.observe(sentinel); },
    disconnect() { io.disconnect(); },
  };
}

Usage example

javascript
const list = document.querySelector('#list');
const { sentinel, observe } = createInfiniteScroll({
  onLoadMore: () => fetchNextPage().then(appendItems),
  hasMore: () => page < totalPages,
});
list.append(sentinel);
observe();

Interview tips

  • Mention virtualization for very long lists (react-window / tanstack virtual).
  • Handle errors and empty states; don’t infinite-loop on failed fetch.

Related

← All snippets