JavaScript Infinite Scroll Pagination
Implement scroll-based data loading in JavaScript with IntersectionObserver: sentinel detection, fetch, loading and error states, and clean teardown.
Overview
Infinite scroll appends the next page of results as the user approaches the end of the list, so nobody has to click “next”. This recipe builds it on IntersectionObserver: a sentinel element sits at the bottom of the list, and when it enters the viewport (plus a rootMargin buffer) the code fetches the next page and appends it. You’ll get a working basic version, a production class with loading and error states plus clean teardown, a scroll-event fallback for older browsers, and a React hook with the subtle bits done right.
When to Use
Infinite scroll fits feeds where content is consumed linearly and item order is stable:
- Social-style feeds, image galleries, activity streams, comment threads
- Mobile-first layouts where scroll is already the primary gesture
- Search results where “next page” clicks show measurable drop-off
It does not fit everywhere. Reach for real pagination (or a “load more” button) when:
| Situation | Better choice | Why |
|---|---|---|
| Users jump to specific items or pages | Numbered pagination | No way to deep-link “page 7” of a stream |
| Content below the list (footer, filters) | Load more button | The list pushes the footer away forever |
| User picks up where they left off | Pagination + scroll restore | Back-nav lands mid-stream with no anchor |
| Content changes fast (new items prepend) | Cursor pagination | Offset ?page=N duplicates or skips items |
| Screen-reader-heavy audience | Load more button | Auto-inserting content is disorienting |
A “load more” button is the honest middle ground: same UX momentum, but the user controls the insert and you can keep focus management simple. It also plays nicer with keyboard-only users — focus never gets hijacked by content materializing under them mid-scroll.
Solution
1. Basic infinite scroll with IntersectionObserver
const sentinel = document.getElementById("sentinel");
const container = document.getElementById("list");
let page = 1;
let loading = false;
let hasMore = true;
async function loadPage(pageNum) {
const res = await fetch(`/api/items?page=${pageNum}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
function renderItems(items) {
for (const item of items) {
const div = document.createElement("div");
div.className = "list-item";
div.textContent = item.title;
container.appendChild(div);
}
}
const observer = new IntersectionObserver(async (entries) => {
if (!entries[0].isIntersecting || loading || !hasMore) return;
loading = true;
page++;
try {
const data = await loadPage(page);
renderItems(data.items);
hasMore = data.hasMore;
if (!hasMore) observer.unobserve(sentinel);
} catch (err) {
page--; // failed fetch doesn't consume the page
console.error("Load failed:", err);
}
loading = false;
});
observer.observe(sentinel);
The try/catch matters: without it, a failed fetch leaves loading stuck at true and the scroll silently stops working; it’s the single most common way this code breaks in production.
2. Complete class with loading, error, and teardown
class InfiniteScroll {
constructor(options) {
this.container = options.container;
this.sentinel = options.sentinel;
this.fetchUrl = options.fetchUrl;
this.renderItem = options.renderItem;
this.pageSize = options.pageSize ?? 10;
this.threshold = options.threshold ?? 200;
this.page = 1;
this.loading = false;
this.hasMore = true;
this.observer = null;
this.controller = null; // in-flight fetch
}
init() {
this.loadInitial();
this.setupObserver();
}
async loadInitial() {
this.showLoading();
try {
const data = await this.fetchPage(1);
this.renderItems(data.items);
this.hasMore = data.hasMore;
} catch (err) {
this.showError("Failed to load initial data");
}
this.hideLoading();
}
setupObserver() {
this.observer = new IntersectionObserver(
(entries) => this.handleIntersection(entries),
{ rootMargin: `${this.threshold}px` }
);
this.observer.observe(this.sentinel);
}
async handleIntersection(entries) {
if (!entries[0].isIntersecting || this.loading || !this.hasMore) return;
this.loading = true;
this.showLoading();
this.controller = new AbortController();
try {
this.page++;
const data = await this.fetchPage(this.page);
this.renderItems(data.items);
this.hasMore = data.hasMore;
if (!this.hasMore) {
this.observer.unobserve(this.sentinel);
this.showEndMessage();
}
} catch (err) {
if (err.name === "AbortError") return; // destroy() cancelled us
this.page--;
this.showError("Failed to load more items. Try scrolling again.");
} finally {
this.controller = null;
this.loading = false;
this.hideLoading();
}
}
async fetchPage(pageNum) {
const url = `${this.fetchUrl}?page=${pageNum}&limit=${this.pageSize}`;
const res = await fetch(url, { signal: this.controller.signal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
renderItems(items) {
const fragment = document.createDocumentFragment();
for (const item of items) {
fragment.appendChild(this.renderItem(item));
}
this.container.appendChild(fragment); // one reflow, not N
}
showLoading() {
let loader = document.getElementById("scroll-loader");
if (!loader) {
loader = document.createElement("div");
loader.id = "scroll-loader";
loader.className = "scroll-loader";
loader.setAttribute("role", "status");
loader.textContent = "Loading more items…";
this.container.parentElement.appendChild(loader);
}
loader.style.display = "block";
}
hideLoading() {
const loader = document.getElementById("scroll-loader");
if (loader) loader.style.display = "none";
}
showError(message) {
let error = document.getElementById("scroll-error");
if (!error) {
error = document.createElement("div");
error.id = "scroll-error";
error.className = "scroll-error";
error.setAttribute("role", "alert");
this.container.parentElement.appendChild(error);
}
error.textContent = message;
error.style.display = "block";
setTimeout(() => { error.style.display = "none"; }, 3000);
}
showEndMessage() {
const end = document.createElement("div");
end.className = "scroll-end";
end.textContent = "You're all caught up.";
this.container.parentElement.appendChild(end);
}
destroy() {
if (this.controller) this.controller.abort();
if (this.observer) {
this.observer.disconnect();
this.observer = null;
}
}
}
// Usage
const list = document.getElementById("list");
const scroll = new InfiniteScroll({
container: list,
sentinel: document.getElementById("sentinel"),
fetchUrl: "/api/posts",
renderItem: (post) => {
const div = document.createElement("div");
div.className = "post-card";
const h3 = document.createElement("h3");
h3.textContent = post.title; // textContent, not innerHTML — no XSS
const p = document.createElement("p");
p.textContent = post.excerpt;
div.append(h3, p);
return div;
},
pageSize: 20,
threshold: 300
});
scroll.init();
// Teardown on SPA route change or page unload
window.addEventListener("beforeunload", () => scroll.destroy());
Three upgrades over the naive version worth stealing: AbortController cancels an in-flight fetch when the page tears down (no phantom append), DocumentFragment turns N appends into one reflow, and role="status"/role="alert" make the loader and error visible to screen readers.
3. Scroll-event fallback with debounce
For environments without IntersectionObserver (really old WebViews, some embedded browsers):
function debounce(fn, delay) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}
let page = 1;
let loading = false;
let hasMore = true;
const handleScroll = debounce(async () => {
const scrollBottom = window.scrollY + window.innerHeight;
const docHeight = document.documentElement.scrollHeight;
if (scrollBottom < docHeight - 300 || loading || !hasMore) return;
loading = true;
page++;
try {
const res = await fetch(`/api/items?page=${page}`);
const data = await res.json();
renderItems(data.items);
hasMore = data.hasMore;
} catch (err) {
page--;
console.error("Load failed:", err);
}
loading = false;
}, 150);
window.addEventListener("scroll", handleScroll, { passive: true });
Check support with "IntersectionObserver" in window and swap strategies accordingly. Honestly though, browser support is ~97% globally, so treat this as the exception path.
4. React hook with a synchronous guard
import { useEffect, useRef, useState, useCallback } from "react";
function useInfiniteScroll(fetchUrl) {
const [items, setItems] = useState([]);
const [page, setPage] = useState(1);
const [loading, setLoading] = useState(false);
const [hasMore, setHasMore] = useState(true);
const sentinelRef = useRef(null);
// Ref, not state, for the guard: two intersection events in the same
// tick both read the state `loading` as false before React re-renders
const loadingRef = useRef(false);
const loadMore = useCallback(async () => {
if (loadingRef.current) return;
loadingRef.current = true;
setLoading(true);
try {
const res = await fetch(`${fetchUrl}?page=${page}`);
const data = await res.json();
setItems(prev => [...prev, ...data.items]);
setHasMore(data.hasMore);
setPage(prev => prev + 1);
} catch (err) {
console.error("Failed to load:", err);
} finally {
loadingRef.current = false;
setLoading(false);
}
}, [fetchUrl, page]);
useEffect(() => {
const sentinel = sentinelRef.current;
if (!sentinel || !hasMore) return;
const observer = new IntersectionObserver(
(entries) => {
if (entries[0].isIntersecting) loadMore();
},
{ rootMargin: "300px" }
);
observer.observe(sentinel);
return () => observer.disconnect();
}, [loadMore, hasMore]);
return { items, loading, hasMore, sentinelRef };
}
function ItemList() {
const { items, loading, hasMore, sentinelRef } = useInfiniteScroll("/api/items");
return (
<div>
{items.map(item => (
<div key={item.id} className="item-card">
{item.title}
</div>
))}
{loading && <p role="status">Loading…</p>}
{hasMore && <div ref={sentinelRef} style={{ height: "1px" }} />}
{!hasMore && <p>You're all caught up.</p>}
</div>
);
}
How It Works
IntersectionObserver watches a target (the sentinel you park at the bottom of the list) and fires when it starts or stops intersecting the viewport, all off the main thread, so it doesn’t jank scrolling the way a scroll listener does. The pieces that make it production-grade:
rootMargingrows the trigger zone:"300px"fires when the sentinel is still 300px below the fold, so content lands before the user hits the gap. It only accepts px and %, with CSS margin syntax (noem, norem).- The
loadingflag serializes the whole flow. Intersection events fire on state changes, not continuously, but a fast scroll can queue several before the first fetch resolves. Guard it synchronously; that’s why the React version uses a ref. hasMorefrom the API is the reliable stop signal. Emptyitemsarrays work as a fallback too, but an explicit flag stays unambiguous when a page legitimately comes back empty.- Offset vs cursor:
?page=N&limit=Mbreaks when items get inserted or deleted mid-scroll (user sees duplicates or gaps). If the dataset is write-heavy, ask the API for cursor pagination (?after=<last-id>); the class swaps one line: build the URL from the last rendered item’s id instead of a page counter. See cursor pagination for the server side. - Teardown is non-negotiable in SPAs:
disconnect()the observer andabort()the in-flight fetch on unmount, or you’ll append into a detached node and leak the observer.
Variants
| Approach | Complexity | Use when |
|---|---|---|
| IntersectionObserver | Low | Default — ~97% browser support |
| Scroll event + debounce | Medium | Legacy WebViews without IO |
| Load more button | Low | Footer exists, deep-linking matters, a11y-critical |
| Cursor-based | Medium | Write-heavy feeds where offsets drift |
| Virtual scroll (react-window) | High | Thousands of rendered items |
Best Practices
- Prefetch with
rootMargin(200-400px) so content lands before the gap is visible. - Guard fetches synchronously: a flag checked and set in the same tick, not React state.
- Stop on
hasMore, andunobservethe sentinel when the feed runs out so it stops firing. - Batch appends through a
DocumentFragment; NappendChildcalls are N reflows. - Cancel in-flight fetches and disconnect the observer on teardown.
- Render with
textContent/createElement, neverinnerHTMLwith API data. - Announce state changes:
role="status"on the loader,role="alert"on errors.
Common Mistakes
- No error path. A rejected fetch without
catchleavesloadingstuck and the scroll dies silently on the first flaky request. - Async-only guards. Checking
loadingfrom React state lets two same-tick events both fetch; use a ref or plain variable. rootMargin: 0. The sentinel must be fully visible before anything loads, so users see a hard gap while the request flies.- Offset pagination on a moving dataset. Page 2 shifts when items prepend; that’s cursor territory.
- Leaking the observer. No
disconnect()on unmount means phantom fetches and retained DOM in SPAs. innerHTMLwith API data. One maliciouspost.titleand you’ve shipped an XSS. UsetextContent.
See Also
Frequently Asked Questions
How is IntersectionObserver better than scroll events?
IntersectionObserver runs off the main thread and only fires on intersection changes, so it doesn't compete with the scroll path. A scroll listener runs on every frame, needs manual throttling, and still polls geometry (scrollY, scrollHeight) on the main thread.
How do I keep thousands of items from bloating the DOM?
Virtual scrolling (react-window, vue-virtual-scroller, or similar) renders only the visible slice plus a buffer, keeping the DOM at ~50 nodes regardless of list size. See virtual lists with react-window.
What should the API response look like?
{
"items": [...],
"page": 2,
"hasMore": true,
"total": 500
}
hasMore is the contract the observer needs; total is optional, useful for a "showing X of Y" indicator though not required.
What if the user scrolls past the sentinel several times quickly?
The loading flag serializes fetches, so at most one request runs at a time. The observer also only fires on intersection changes, so it won't re-trigger while the sentinel stays visible, only when it enters or leaves.
Does infinite scroll hurt SEO?
It can. Googlebot doesn't scroll, so anything below the fold that only renders on intersection never gets crawled, so page 2 onwards might as well not exist for search. That's fine for app-style feeds behind intent-driven navigation, but for indexable content (blog archives, product listings, docs), keep real paginated URLs or server-render at least the first pages and let infinite scroll enhance from there.
Can the browser restore scroll position on back-navigation?
Mostly yes: the browser scroll-restores to the document height it remembers, but pages loaded via infinite scroll aren't re-fetched, so the list only has page 1 again and the user lands back at the top of a shorter page. If back-nav matters, stash loaded pages in sessionStorage and replay them on mount (cache items, page, hasMore and scroll offset), or switch to real pagination where URLs carry the state themselves.
Related Resources
Debounce and Throttle Functions in JavaScript
Control function execution rate with debounce and throttle. Covers leading and trailing edge, cancelable timers, and real-world use cases.
RecipeJavaScript Service Worker Offline Caching for PWA
Serve your web app offline with Service Workers and the Cache API: precaching, runtime caching strategies and a fallback page.
RecipeVirtualize Long Lists with react-window
How to render large lists efficiently in React using react-window for DOM virtualization, including fixed and variable height rows and grid layouts.
RecipeCursor-Based Pagination in PostgreSQL (Keyset vs OFFSET)
Implement efficient cursor-based pagination for large datasets in PostgreSQL, avoiding OFFSET performance degradation with indexed keyset pagination and stable sort ordering
RecipeImplement Lazy Loading for Images, Components, and Data
How to defer loading of non-critical resources until needed, improving initial page load time, reducing bandwidth, and optimizing Core Web Vitals.
PatternEager Loading Pattern: Fix the N+1 Problem
Load related data in a single query rather than multiple round-trips, preventing the N+1 problem and improving read performance.