Infinite scrolling using Intersection Observer API

trex777

Manish Kumar Sahu

Posted on July 6, 2021

Infinite scrolling using Intersection Observer API

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

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>
Enter fullscreen mode Exit fullscreen mode
  • All the images will be appended in the div element having id="root.
  • Whenever user scrolls to the bottom of the page, div element having id="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)
  }
}
Enter fullscreen mode Exit fullscreen mode

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);
})
Enter fullscreen mode Exit fullscreen mode

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 take window by default. rootMargin is just the CSS property for the root element. And threshold 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 calling fetchImage() 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 ✌

Cover Image

💖 💪 🙅 🚩
trex777
Manish Kumar Sahu

Posted on July 6, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related