Reading list Switch to dark mode

    Intersection Observer in Javascript

    Updated 13 December 2019

    Today we will discuss about the Intersection Observer api in Javascript with example. So starting from why do we need Intersection Observer api in Javascript?

    where do we will apply it ? and most importantly what is Intersection Observer api ?

    lets understand one by one.

    What is Intersection Observer api ?

    Intersection Observer asynchronously observe changes in the target element with the top-level document’s viewport.

    We will have a target element each time which will be observed. Whenever the target meets a threshold specified for the IntersectionObserver, the callback is invoked. The callback receives a list of  objects and the observer. We will have a complete example for the above definition.

    Start your headless eCommerce
    now.
    Find out More

    There are other questions remaining as mentioned above lets explore them as well.

    Why do we need Intersection Observer api in Javascript?

    As we all know about lazy loading concept, for further details about lazy loading look at this tutorial from developer google .

    The basic concept of lazy loading is to reduce as much as HTTP Request from server. Each image request treat as a HTTP request so if a page consist of 50 image approx then it consist of atleast 5o HTTP request which makes slow load time of site. and less interaction of user on site.

    So lazy loading can be implemented on such cases where only such viewport images will be loaded on page while other images will be loaded on scroll by end user.

    lazy loading concept can be implemented in various ways by developers using javascript and of core implementation using   Intersection Observer api.

    Problem Faced While Own lazy loading concept using calculation via javascript –

    Few Drawbacks are mentioned below –

    • This can cause performance issues as the calculations will be run on the main thread.
    • The calculation is performed each time there is a scroll on the page which is bad if the image is well below the view port
    • if there are a huge number of images in the page, then calculation  made on image can be very costly.

    Lazy loading using Intersection Observer follows the following steps:

    • Create a new intersection observer
    • Watch the element we want to lazy load for visibility changes
    • When the element is in viewport, load the element
    • Once the element is loaded, stop watching it for visibility changes

    where do we will apply it ?

    We can apply Intersection Observer api in lazy loading concept for example.

    lets take a look at an example below

     

    <html>
      <head>
    
        <style>
        
        .boxy {
          overflow-y: scroll;
          background: #f1f1f1;
        }
        .woo-image {
          display: flex;
          align-items: center;
          justify-content: center;
          background-color: #f8f8f8;
          color: #333;
          height: 250px;
          margin-bottom: 250px
        }
        .active {
          background-color: #999;
        }
        
        </style>
    
      </head>
      <body>
    
          <div class="boxy" id="wooBox">
              <div class="woo-image">
                <h2>woo image</h2>
              </div>
              <div class="woo-image">
                <h2>woo image</h2>
              </div>
              <div class="woo-image">
                <h2>woo image</h2>
              </div>
              <div class="woo-image">
                <h2>woo image</h2>
              </div>
              <div class="woo-image">
                <h2>woo image</h2>
              </div>
              <div class="woo-image">
                <h2>woo image</h2>
              </div>
              <div class="woo-image">
                <h2>woo image</h2>
              </div>
              <div class="woo-image">
                <h2>woo image</h2>
              </div>
              <div class="woo-image">
                <h2>woo image</h2>
              </div>
              <div class="woo-image">
                <h2>woo image</h2>
              </div>
            </div>
         <script>
    
        window.addEventListener('load',function(){
           
            const options = {
              rootMargin: "25px",
              threshold: 1.0
            };
            const io = new IntersectionObserver(entries => {
              entries.forEach(entry => {
                console.log('entry: ', entry);
                if (entry.intersectionRatio > 0.9) {
                  entry.target.classList.add('active');
                  entry.target.innerHTML = '<h2>Woo!</h2>';
                  io.unobserve(entry.target);
                }
              });
            }, options);
    
            const targetElements = document.querySelectorAll(".woo-image");
            for (let element of targetElements) {
              // console.log('element: ', element);
              io.observe(element);
            }
    
          });
        </script>
    
      </body>
    
    </html>
    
    

    This is just a basic example you can apply the concept on projects easily.

    Happy coding just every bit details of syntax here Developer MDN.

    Do let me know your thoughts and i will writing the same code on react and other Observers like mutation observer and Performance Observer In coming series with details

     

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home