Start codelab

Codelab Flow

What you will learn

L P Progressive Loading

In this codelab you will learn how to add Progressive Loading to your PWA by lazy-loading of images as a page is scrolled.

Using Intersection Observer API you can load target images only when the user scrolls down, causing them to display in the viewport. This is already implemented on the home page and is so magical.

Setting up

Make sure your <img /> tags have the src and a data-src arttributes set to image source url as shown in the example below:

Note : You can have an alernative paceholder image say for user avatar display photo or just as shown below using the same image to be lazy-loaded.

<img src="./images/logo/jengalogohorizontal.png" data-src="./images/logo/jengalogohorizontal.png" alt="loading image.." />

Create an empty app.loading.js in your project and copy the code snippet provided here.
Copy the code snippet below to your app.loading.js and save.
   
  // Learn more at : https://pwafire.org

  let imagesToLoad = document.querySelectorAll('img[data-src]');

  let loadImages = (image) => {
      image.setAttribute('src', image.getAttribute('data-src'));
      image.onload = () => {
          image.removeAttribute('data-src');
      };
  };

  if ('IntersectionObserver' in window) {
      let observer = new IntersectionObserver((items, observer) => {
          items.forEach((item) => {
              if (item.isIntersecting) {
                  loadImages(item.target);
                  observer.unobserve(item.target);
              }
          });
      });
      imagesToLoad.forEach((img) => {
          observer.observe(img);
      });
  } 
   else {
      imagesToLoad.forEach((img) => {
          loadImages(img);
      });
  }
    

To your page's main styles copy the following code snippet to it to style up the loading...

 img[data-src] {
        filter: blur(0.2em);
      }
        
 img  {
        filter: blur(0em);
        transition: filter 0.5s;
      }

What's next?

Read more in detail on mdn docs here

Edit on Github