Introduction
Infinite scrolling is a way to organize the contents of the pages in a website. This allows the user to browse all the contents in a single webpage by scrolling down. When the user reaches the bottom of the page, more contents load automatically.
In this article, we will discuss infinite scrolling and how to implement it using Intersection Observer API
.
Usage
Let's say a website has 100+ posts to show, but it can't just load all the posts altogether otherwise it will consume that much data and will take much time to load all the posts which ruins the user experience.
So the website will just load the first 10 posts (which will consume very little data and time to load). Then, whenever the user almost reaches the bottom of the page, the next 10 posts will load. In this way, the posts will load and make the user experience better.
Mostly social media websites like Facebook and Twitter implemented infinite scrolling in their user feed pages.
Long and endless pages are good for time-killing activities because users arein the mindset for smooth exploration and discovery, which results in higher engagement of users in the website.
But, not every website should implement this, specially the goal oriented website like e-commerce sites, because when user wants to revisit some product page, it is difficult to find it, in this case pagination is really helpful.
Implementaion
We will implement this by using an array of 20 images. First only 5 images will be loaded, then as the user scrolls down and reaches the bottom of the page, more 5 photos will load, this will continue till all the images are loaded.
Setup
HTML
<body>
<h1>Oberserver Intersection API</h1>
<div id="root"></div>
<div id="loading">Loading...</div>
<script src="script.js"></script>
</body>
- All the images will be appended in the
div
element havingid="root
. - Whenever user scrolls to the bottom of the page,
div
element havingid="loading"
will be shown.
Javascript
We will be using fetchImage()
which when called fetches 5 images from the array of 20 images. Here, fetchImages()
can be any server API call.
function fetchImage() {
if (imgCount !== 20) {
setTimeout(() => {
for (let i = imgCount; i < imgCount + 5; i++) {
const image = document.createElement("img");
image.src = data[i].src;
rootElement.append(image);
}
imgCount += 5;
}, 500)
}
}
Now we can setup the Intersection Observer API
document.addEventListener("DOMContentLoaded", () => {
let options = {
root: null,
rootMargin: "0px",
threshold: 0.25
};
function handleIntersect(entries, observer) {
entries.forEach((entry) => {
if (entry.isIntersecting) {
if (imgCount !== 20) {
fetchImage()
}
}
});
}
let observer = new IntersectionObserver(handleIntersect,
options);
observer.observe(loader);
})
Lets analyse what is happening in the above code.
We are calling
InterectionObserver()
which takes two parameters, first one is a callback which would decide what will happen when intersection happens, second parameter is a set of options.In
options
,root
will be the element with which intersection occurs, by defining it as null means it will takewindow
by default.rootMargin
is just the CSS property for the root element. Andthreshold
can be an array of ratios which when passed can decide on what intersection ratio, the callback should be executed.In
handleIntersect()
, we are checking if the loader is intersected, then we are callingfetchImage()
to fetch 5 more images.Atlast, we are calling the
observer
to observe loader. That means we are targeting the loader, whenever it appears in the viewport, we will load 5 more images.
You can view the full code setup here.
Conclusion
Infinite scrolling can be done in other ways, in the on scroll approach, every time a user scrolls, but we have to keep calculating scroll positions and can debounce for delays.
While using Intersection Observer API
, the callback will be fired only when the target element comes to the viewport which prevents the javascript engine to run unnecessary calls.
You can explore more about Intersection Observer API here
Hope you enjoyed it ✌
Top comments (3)
Nice article 👍🏼
I just want to give my opinion about the concept of infinit scrolling, and it has not a good user experience. And if you click on a link by mistake, when you go back, you have to scroll all the back down
Yes totally, that's why I mentioned that not every website should implement this, a hybrid of pagination and infinite scrolling is the best option I think.
Yh that's a very annoying experience but can be solved by storing the scroll position in a cookie or in local storage.