Infinite Scroll Implementation in JavaScript
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Infinite Scroll runs in O(n) time and O(n) space, in JavaScript as in every other language.
- ✓IntersectionObserver is a browser global, not a package. Construct it with a callback and an options object of root, rootMargin and threshold, call observe(el) on a sentinel node, then read isIntersecting and intersectionRatio off each IntersectionObserverEntry; unobserve detaches one target and disconnect detaches all.
- ✓One sentinel after the list, never an observer per row; a thousand observed targets is a thousand entries the browser has to compute intersections for.
- ✓The JavaScript trap: Two IntersectionObserver behaviours bite here and nowhere else. First, observe() itself queues an initial notification, so the callback runs once before any scrolling with isIntersecting already true if the sentinel starts on screen; a callback that fetches unconditionally fetches at page load.
- ✓The observer costs nothing per scroll event, which is its entire purpose: crossings are computed off your handler instead of by it at 120 Hz.
What Infinite Scroll actually is
Infinite Scroll in JavaScript: what you actually reach for
JavaScript implementation
const feed = document.getElementById("feed");
const sentinel = document.getElementById("sentinel");
let cursor = null;
let exhausted = false;
let inFlight = null;
// rootMargin arms one viewport early. observe() alone queues an immediate
// callback, so the guard below has to be the thing that decides, not the call.
const io = new IntersectionObserver(onIntersect, { rootMargin: "600px 0px" });
io.observe(sentinel);
function onIntersect(entries) {
for (const entry of entries) {
if (entry.isIntersecting && !inFlight && !exhausted) void loadNext();
}
}
async function loadNext() {
const ctrl = new AbortController();
inFlight = ctrl;
try {
const url = new URL("/api/tremors", location.origin);
if (cursor) url.searchParams.set("after", cursor);
const res = await fetch(url, { signal: ctrl.signal });
const { items, next } = await res.json();
const frag = document.createDocumentFragment();
for (const t of items) {
const row = document.createElement("article");
row.style.blockSize = "72px"; // reserve height so nothing reflows on paint
row.textContent = `M ${t.magnitude}`;
frag.append(row);
}
feed.insertBefore(frag, sentinel); // one reflow, sentinel stays last child
cursor = next;
if (next === null) {
exhausted = true;
io.unobserve(sentinel);
sentinel.remove();
} else if (sentinel.getBoundingClientRect().top < innerHeight) {
loadNext(); // still on screen: no new crossing will ever be reported
}
} catch (err) {
if (err.name !== "AbortError") throw err;
} finally {
inFlight = null;
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe JavaScript-specific trap
Performance in JavaScript, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which JavaScript type or library should I use for Infinite Scroll?
IntersectionObserver is a browser global, not a package. Construct it with a callback and an options object of root, rootMargin and threshold, call observe(el) on a sentinel node, then read isIntersecting and intersectionRatio off each IntersectionObserverEntry; unobserve detaches one target and disconnect detaches all. Around it, AbortController with fetch(url, {signal}) cancels a page the reader has already scrolled past, document.createDocumentFragment collapses the append into one layout pass, and URL with searchParams builds the cursor query. Scroll anchoring is CSS rather than script: the overflow-anchor property, enabled by default in every browser that implements it, is what holds reading position when a node lands above the viewport.
What is the most common JavaScript mistake when implementing Infinite Scroll?
Two IntersectionObserver behaviours bite here and nowhere else. First, observe() itself queues an initial notification, so the callback runs once before any scrolling with isIntersecting already true if the sentinel starts on screen; a callback that fetches unconditionally fetches at page load. Second, entries are delivered on transitions, not on states. If the rows you just appended did not push the sentinel out of the root box plus rootMargin, nothing crossed anything, no further entry ever arrives, and the feed silently stops one page in. Measure with getBoundingClientRect after each append and keep loading while it is still inside the viewport.
How does Infinite Scroll actually perform in JavaScript?
The observer costs nothing per scroll event, which is its entire purpose: crossings are computed off your handler instead of by it at 120 Hz. Growth is the real cost. Attached nodes are never collected, so a 200-page session is holding ten thousand elements with layout boxes and computed style attached to each. Appending through a DocumentFragment buys one reflow instead of one per row. Past a few thousand rows the honest answer is windowing, keeping a fixed number of nodes over a spacer element, at which point the sentinel moves with the window rather than sitting at the end. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialMost AI and dev tools have a student plan. See which ones and how to claim them on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.