Infinite Scrolling in Modern Web Apps
Infinite scrolling is one of the most commonly asked topics in coding interviews and widely used in real-world applications like social media feeds, e-commerce sites, and content platforms.
So for implementing the Infinite scroll we need to understand the intersection observer, so before jumping directly into Intersection Observer, it's important to understand some foundational concepts that power traditional infinite scrolling.
1. Understanding Viewport Height
What is window.innerHeight (Viewport Height)?
The viewport height is the visible area of the browser where content is displayed.
window.innerHeight
This gives the height of the visible screen (excluding browser UI like address bar)
What is document.documentElement.scrollHeight?
This represents the total height of the webpage, including content that is not currently visible (scrollable part).
document.documentElement.scrollHeight
What is document.documentElement.scrollTop?
This tells how much the user has already scrolled from the top.
document.documentElement.scrollTop
2. Traditional Infinite Scrolling Approach
Before modern APIs, developers used scroll events + calculations.
Logic:
When user scrolls near the bottom → Load more data
Condition:
window.innerHeight + document.documentElement.scrollTop >= document.documentElement.scrollHeight - 10
This means:
Visible screen height + Scrolled amount = Total page height
If true → user reached bottom
Example Implementation:
window.addEventListener("scroll", () => {
const scrollTop = document.documentElement.scrollTop;
const scrollHeight = document.documentElement.scrollHeight;
const clientHeight = window.innerHeight;
if (scrollTop + clientHeight >= scrollHeight - 10) {
console.log("Load more data...");
// API call here
}
});
Problems with Traditional Approach
Performance Issues
Scroll event fires many times (very frequently)
Can cause lag if not optimized
Manual Calculations
You have to calculate everything yourself
Needs Throttling/Debouncing
Otherwise too many API calls
3. Modern Approach: Intersection Observer
Now comes the real game changer.
Instead of listening to scroll events, we observe when an element enters the viewport.
What is Intersection Observer?
It is a browser API that allows you to detect when an element is visible on the screen.
No manual scroll calculations
No performance issues like scroll events
Concept:
Add a "sentinel" div at the bottom
When it becomes visible → Load more data
Example:
const observer = new IntersectionObserver((entries) => {
const entry = entries[0];
if (entry.isIntersecting) {
console.log("Load more data...");
// API call here
}
});
const target = document.querySelector("#load-more");
observer.observe(target);
Top comments (0)