Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Infinite Scroll Implementation in JavaScript

14 min readintermediate
Website QA and SEO audits

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 replaces the page-number control with a trigger: as the reader nears the end of what has been rendered, the next slice is fetched and appended. Two decisions determine whether this is smooth or wretched, and neither is the spinner. The first is how the next slice is asked for. OFFSET re-walks and discards every row before the window, so page 400 costs four hundred times page 1, and a row inserted while the reader is scrolling shifts every boundary, which surfaces as duplicated rows and silently skipped ones. Keyset pagination, also called cursor pagination, instead sends the sort key of the last row already delivered and asks for rows strictly after it. That turns the read into one index descent costing the same on page 400 as on page 1, and it stays correct while the underlying set changes beneath it. The second is how arrival is detected. Sampling scroll offsets runs work on every scroll event, on the thread that also has to paint. The better shape is a sentinel element watched asynchronously, so the platform reports the crossing rather than the page interrogating it. Then the part everyone forgets: the rendered list only grows, and every appended node is memory the reader will never scroll back to. The eight languages split three ways. Two are the browser and own the sentinel, the scroll box and the growing node list directly. One is a native client whose list is lazy by construction, which turns the trigger into a view-lifecycle question. The other five sit on the server end of the same contract, where infinite means a result set walked in bounded windows rather than materialised, and they disagree sharply about who owns the database cursor and when it is released. One of the five has no standard library answer at all and expresses the window as a borrow the compiler refuses to let escape.

Infinite Scroll in JavaScript: what you actually reach for

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.

JavaScript implementation

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. rootMargin does the prefetching, so nobody writes a scrollTop threshold by hand any more. Re-entrancy is guarded with an in-flight flag rather than debounce, because the callback is not throttled in a way you control. The sentinel stays the last child, which makes insertBefore the natural append. And the observer is disconnected when the cursor comes back null, rather than left running against a removed node.
javascript
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 Free

The JavaScript-specific 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. 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.

Performance in JavaScript, beyond the O(n)

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. The asymptotic cost is the same in every language, O(n) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Infinite Scroll between languages.

Real-World Applications

Infinite Scroll is used extensively in production software: web frameworks, content management systems, API gateways, and SPA architectures implement this pattern for handling HTTP requests and rendering. In JavaScript specifically, frameworks like React, Express, and Next.js implement related concepts. Understanding Infinite Scroll helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Infinite Scroll appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Infinite Scroll over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Infinite Scroll to build pattern recognition. In JavaScript, demonstrate proficiency with closures and async/await to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic JavaScript code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Most AI and dev tools have a student plan. See which ones and how to claim them on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Want 50 audits a day? Explore SeekerPro

Engagement

0

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.