JavaScript Projects
Build an Infinite Scroll Feed
Build a production-grade Infinite Scroll Feed in JavaScript. Learn to use IntersectionObserver, manage page pagination state, handle loading indicators, and prevent duplicate requests.
1. Introduction
An Infinite Scroll Feed automatically loads and appends the next page of content as the user approaches the bottom of the current feed, eliminating traditional pagination buttons. Modern implementations use the IntersectionObserver API for efficient viewport tracking.
2. Why It Matters
Legacy implementations calculated scroll positions inside window.onscroll event listeners. Running calculations on every scroll pixel causes main-thread thrashing. IntersectionObserver runs asynchronously on the browser's compositor thread, triggering fetch operations only when a designated target element intersects the viewport.
3. Real-World Analogy
Think of a Conveyor Belt Buffet:
- Legacy Scroll (Constant shouting): Every 2 seconds, you check if the food plate is empty by calling the kitchen. Even if you're not eating, you keep checking.
- IntersectionObserver (Sensor Sentinel): A sensor is placed near the end of the plate. When the last slice of pizza touches the sensor (sentinel element visible in viewport), a signal automatically alerts the chef to bring out the next tray (fetch next page).
4. Feed Architecture & State Management
5. Practical DOM Example
6. Preventing Race Conditions & Duplicate Requests
A critical challenge in infinite scrolling is preventing concurrent duplicate requests when users scroll rapidly. Utilizing an isLoading boolean guard combined with AbortController guarantees single-flight network requests:
7. Common Mistakes
- Forgetting rootMargin pre-fetching: Leaving
rootMarginat0pxforces the user to hit the bottom of the page and pause while waiting for data. SettingrootMargin: '200px'triggers page requests before the user reaches the end, providing a seamless experience.
8. Quick Quiz
Q1: What is the primary benefit of rootMargin in an IntersectionObserver infinite feed?
A) It scales image asset dimensions dynamically
B) It expands the virtual bounding box, allowing data pre-fetching before the sentinel enters the visible screen
Answer: B — rootMargin expands the observer margin, initiating page fetches before the user reaches the end of the content.
9. Scenario-Based Challenge
The Virtualized List Recycling Challenge:
When an infinite feed loads 1,000+ items, DOM memory bloats and scrolling stutters. Extend the feed architecture to implement DOM node recycling (windowing/virtualization), unmounting off-screen DOM nodes above the viewport while preserving scroll height offsets.
10. Debugging Exercise
Explain why this infinite scroll loop sends 10 duplicate API requests on page load, and how to fix it:
// Buggy Feed Setup
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
// Bug: Doesn't check if a request is ALREADY in flight!
fetchDataAndAppend();
}
});
observer.observe(sentinel);
View Solution
Diagnosis: On initial load before items fill the screen, the sentinel remains continuously visible in the viewport. IntersectionObserver triggers multiple callback notifications while fetchDataAndAppend is still waiting for network responses, flooding the server with duplicate page requests.
Fix: Enforce an isLoading flag guard during request execution:
let isLoading = false;
const observer = new IntersectionObserver(async (entries) => { if (entries[0].isIntersecting && !isLoading) { isLoading = true; await fetchDataAndAppend(); isLoading = false; } }); observer.observe(sentinel);
11. Interview Questions
🟢 Q1: Compare IntersectionObserver vs window.onscroll event listeners for infinite scrolling.
Answer:
• window.onscroll: Runs synchronously on the browser's main thread on every scroll pixel. Requires custom throttling and manual getBoundingClientRect() calculations, which can trigger layout thrashing and stuttering.
• IntersectionObserver: Runs asynchronously managed by the browser engine. Triggers callbacks only when elements cross specified visibility thresholds, causing zero main-thread layout thrashing.
12. Production Considerations
- • Footer Accessibility: If a page has an infinite scroll feed, users can never reach the website footer. Place footer links in a collapsible sidebar or secondary navigation menu to maintain accessibility.