Blog Post

Optimizing Website Performance: Harnessing the Power of Image Lazy Loading

Published
May 30, 2023
#
 mins read
By 

in this blog post

In today’s fast-paced digital world, website speed is crucial in retaining attention. One of the ways to achieve faster website loading times is by implementing Image lazy loading. This technique ensures images are loaded only when visible on the user’s screen, reducing the initial load time and improving the website’s overall performance. In this article, we will explore the concept of image lazy loading, how it works, and the different methods to implement it on a website.

What is image lazy loading?

Image lazy loading is a technique used in web development to optimize the loading of images on web pages. The idea behind lazy loading is to defer the loading of images until they are needed, typically when they are visible within the user’s viewport or close to it.

Sample of lazy loading

When lazy loading is implemented, a placeholder or a low-resolution thumbnail image will be used, in place of the actual image, to occupy the space where the actual image will be loaded, providing a visual indication to the user that an image is intended to appear in that location. As the user scrolls down or interacts with the page, JavaScript monitors the position of the images on the page and loads them only when they are close to being visible. This approach helps reduce the amount of data that needs to be loaded initially, improving the page load time and reducing the overall bandwidth usage.

As shown in the sample travel website on the right, while the images below the fold are deferred, all the images within the viewport are loaded, giving the user a sense of the website’s look and feel.  

How to check if the images on a site are lazy loaded:   

  1. Open an incognito window.
  1. Launch developer tools. 
  1. Paste the URL in the address bar and load the page (Don’t perform any actions on the page, like scrolling or clicking on elements).
  1. In the developer tools window, go to the Network tab and click on “IMG”.
  1. A list of requested images will be displayed.
  1. Scroll through each image and observe if it appears on the screen (above the fold content)
  1. If an image cannot be seen on the screen but is still visible in the developer tools preview, the image is not being lazy loaded.
Graphical user interface, website - how to see lazy load

Or run the script below that lists all images that don’t have loading= “lazy” or [data-src] (lazy loading via JS) and are not in the viewport.

function LazyLoad() {
  let Images = document.querySelectorAll(
    'img:not([data-src]):not([loading="lazy"])'
  );
  return Array.from(Images).filter((tag) => !Viewport(tag));
}

function Viewport(tag){
  let viewport = tag.getBoundingClientRect();
  return (
    viewport.bottom >= 0 &&
    viewport.right >= 0 &&
    viewport.top <= (window.innerHeight || document.documentElement.clientHeight) &&
    viewport.left <= (window.innerWidth || document.documentElement.clientWidth)
  );
}

console.log(
  “List of images that are not Lazy Loaded: “,
  LazyLoad()
);

Implementing image lazy loading on a site

There are several ways to implement lazy image loading on a website:

Native lazy loading

Modern browsers support the loading= “lazy” attribute, allowing images to be lazily loaded without additional JavaScript. You simply add the loading= “lazy” attribute to the image tag.  

The “loading” attribute in the HTML “img” tag can have three possible values: “lazy”, “eager”, or “auto.”  

The “lazy” value tells the browser to defer the loading of the image until it is near the visible area of the webpage, which can significantly improve website loading times and user experience.

<img src="image.jpg" loading="lazy" alt="Example Image">

The “eager” value, on the other hand, tells the browser to load the image immediately, even if it is not yet visible. This can be useful for images that are essential for the initial rendering of the page or for images that need to be loaded quickly, regardless of their position on the page.

<img src="image.jpg" loading="eager" alt="Example Image">

The “auto” value is the default value and lets the browser determine when and how to load the image based on its own algorithms and settings.

<img src="image.jpg" loading="auto" alt="Example Image">

After conducting a no-code experiment using Catchpoint WebPageTest, we observed a faster page load when we added the loading= “lazy” attribute to images that were outside the viewport. The results are depicted below.  

filmstrip view of page load

Intersection Observer API

Intersection Observer API is a JavaScript API that allows you to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document’s viewport. You can use this API to detect when an image enters the viewport and then load it dynamically using JavaScript.

<img data-src="path/to/image.jpg" alt="My Image">

<script>
  const images = document.querySelectorAll('img[data-src]');

  const options = {
    rootMargin: ‘0px’,
    threshold: 0.5
  };

  const observer = new IntersectionObserver((entries, observer) => {
    // Loop through each entry
    entries.forEach(entry => {
      // Check if the entry is intersecting the viewport
      if (entry.isIntersecting) {
        // Get the target element
        const img = entry.target;

        // Replace the src attribute with the data-src attribute
        img.src = img.dataset.src;

        // Unobserve the target element to avoid unnecessary updates
        observer.unobserve(img);
      }
    });
  }, options);

  // Observe each image element
  images.forEach(img => {
    observer.observe(img);
  });
</script> 

Third-party JavaScript libraries

There are many third-party libraries available that can help you implement lazy loading. These libraries often provide additional features like support for responsive images, preloading, and more.  

Here are a few third-party js libraries that can help lazy image loading:  

**To ensure successful implementation of image lazy loading with a third-party library, it’s crucial to consider compatibility with diverse browsers and devices, and the possibility of conflicting with other scripts on the website. Additionally, testing the performance of the lazy loading implementation is necessary to confirm that it positively impacts the user experience. **  

Dos and Don’ts of lazy loading  

Dos:  

  • Do lazy load images not immediately visible to the user, such as those below the fold or off-screen.  
  • Do use responsive images with lazy loading to provide an optimal image for the user’s screen size and resolution.  
  • Do consider lazy loading images that are part of image galleries or sliders or carousels, but are not initially visible in the viewport.
  • Do test the lazy loading implementation on various devices and browsers to ensure compatibility and proper functioning.  

Don’ts:  

  • Don’t lazy load critical images that are required for website functionality, such as a LCP images, logo or navigation menu.  
  • Don’t lazy load images that are very small in file size and load quickly, as the overhead of the lazy loading script may not be worth it.  
  • Don’t forget to provide alternate content for non-lazy loaded images, such as alt text or a noscript tag, to ensure accessibility.  
  • Don’t use lazy loading as a substitute for optimizing images for web use, as large or uncompressed images can still negatively impact performance.  

In conclusion, image lazy loading is a powerful technique that can help improve website performance by reducing the initial page load time and overall bandwidth usage. With the availability of modern browsers and JavaScript APIs like the Intersection Observer API, implementing lazy loading has become easier than ever. By adopting lazy loading, you’ll improve website performance and enhance user experience, resulting in increased engagement and higher conversion rates.  

Curious about the impact of lazy loading on your website’s loading times? Visit Catchpoint WebPageTest and run a test for free.

In today’s fast-paced digital world, website speed is crucial in retaining attention. One of the ways to achieve faster website loading times is by implementing Image lazy loading. This technique ensures images are loaded only when visible on the user’s screen, reducing the initial load time and improving the website’s overall performance. In this article, we will explore the concept of image lazy loading, how it works, and the different methods to implement it on a website.

What is image lazy loading?

Image lazy loading is a technique used in web development to optimize the loading of images on web pages. The idea behind lazy loading is to defer the loading of images until they are needed, typically when they are visible within the user’s viewport or close to it.

Sample of lazy loading

When lazy loading is implemented, a placeholder or a low-resolution thumbnail image will be used, in place of the actual image, to occupy the space where the actual image will be loaded, providing a visual indication to the user that an image is intended to appear in that location. As the user scrolls down or interacts with the page, JavaScript monitors the position of the images on the page and loads them only when they are close to being visible. This approach helps reduce the amount of data that needs to be loaded initially, improving the page load time and reducing the overall bandwidth usage.

As shown in the sample travel website on the right, while the images below the fold are deferred, all the images within the viewport are loaded, giving the user a sense of the website’s look and feel.  

How to check if the images on a site are lazy loaded:   

  1. Open an incognito window.
  1. Launch developer tools. 
  1. Paste the URL in the address bar and load the page (Don’t perform any actions on the page, like scrolling or clicking on elements).
  1. In the developer tools window, go to the Network tab and click on “IMG”.
  1. A list of requested images will be displayed.
  1. Scroll through each image and observe if it appears on the screen (above the fold content)
  1. If an image cannot be seen on the screen but is still visible in the developer tools preview, the image is not being lazy loaded.
Graphical user interface, website - how to see lazy load

Or run the script below that lists all images that don’t have loading= “lazy” or [data-src] (lazy loading via JS) and are not in the viewport.

function LazyLoad() {
  let Images = document.querySelectorAll(
    'img:not([data-src]):not([loading="lazy"])'
  );
  return Array.from(Images).filter((tag) => !Viewport(tag));
}

function Viewport(tag){
  let viewport = tag.getBoundingClientRect();
  return (
    viewport.bottom >= 0 &&
    viewport.right >= 0 &&
    viewport.top <= (window.innerHeight || document.documentElement.clientHeight) &&
    viewport.left <= (window.innerWidth || document.documentElement.clientWidth)
  );
}

console.log(
  “List of images that are not Lazy Loaded: “,
  LazyLoad()
);

Implementing image lazy loading on a site

There are several ways to implement lazy image loading on a website:

Native lazy loading

Modern browsers support the loading= “lazy” attribute, allowing images to be lazily loaded without additional JavaScript. You simply add the loading= “lazy” attribute to the image tag.  

The “loading” attribute in the HTML “img” tag can have three possible values: “lazy”, “eager”, or “auto.”  

The “lazy” value tells the browser to defer the loading of the image until it is near the visible area of the webpage, which can significantly improve website loading times and user experience.

<img src="image.jpg" loading="lazy" alt="Example Image">

The “eager” value, on the other hand, tells the browser to load the image immediately, even if it is not yet visible. This can be useful for images that are essential for the initial rendering of the page or for images that need to be loaded quickly, regardless of their position on the page.

<img src="image.jpg" loading="eager" alt="Example Image">

The “auto” value is the default value and lets the browser determine when and how to load the image based on its own algorithms and settings.

<img src="image.jpg" loading="auto" alt="Example Image">

After conducting a no-code experiment using Catchpoint WebPageTest, we observed a faster page load when we added the loading= “lazy” attribute to images that were outside the viewport. The results are depicted below.  

filmstrip view of page load

Intersection Observer API

Intersection Observer API is a JavaScript API that allows you to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document’s viewport. You can use this API to detect when an image enters the viewport and then load it dynamically using JavaScript.

<img data-src="path/to/image.jpg" alt="My Image">

<script>
  const images = document.querySelectorAll('img[data-src]');

  const options = {
    rootMargin: ‘0px’,
    threshold: 0.5
  };

  const observer = new IntersectionObserver((entries, observer) => {
    // Loop through each entry
    entries.forEach(entry => {
      // Check if the entry is intersecting the viewport
      if (entry.isIntersecting) {
        // Get the target element
        const img = entry.target;

        // Replace the src attribute with the data-src attribute
        img.src = img.dataset.src;

        // Unobserve the target element to avoid unnecessary updates
        observer.unobserve(img);
      }
    });
  }, options);

  // Observe each image element
  images.forEach(img => {
    observer.observe(img);
  });
</script> 

Third-party JavaScript libraries

There are many third-party libraries available that can help you implement lazy loading. These libraries often provide additional features like support for responsive images, preloading, and more.  

Here are a few third-party js libraries that can help lazy image loading:  

**To ensure successful implementation of image lazy loading with a third-party library, it’s crucial to consider compatibility with diverse browsers and devices, and the possibility of conflicting with other scripts on the website. Additionally, testing the performance of the lazy loading implementation is necessary to confirm that it positively impacts the user experience. **  

Dos and Don’ts of lazy loading  

Dos:  

  • Do lazy load images not immediately visible to the user, such as those below the fold or off-screen.  
  • Do use responsive images with lazy loading to provide an optimal image for the user’s screen size and resolution.  
  • Do consider lazy loading images that are part of image galleries or sliders or carousels, but are not initially visible in the viewport.
  • Do test the lazy loading implementation on various devices and browsers to ensure compatibility and proper functioning.  

Don’ts:  

  • Don’t lazy load critical images that are required for website functionality, such as a LCP images, logo or navigation menu.  
  • Don’t lazy load images that are very small in file size and load quickly, as the overhead of the lazy loading script may not be worth it.  
  • Don’t forget to provide alternate content for non-lazy loaded images, such as alt text or a noscript tag, to ensure accessibility.  
  • Don’t use lazy loading as a substitute for optimizing images for web use, as large or uncompressed images can still negatively impact performance.  

In conclusion, image lazy loading is a powerful technique that can help improve website performance by reducing the initial page load time and overall bandwidth usage. With the availability of modern browsers and JavaScript APIs like the Intersection Observer API, implementing lazy loading has become easier than ever. By adopting lazy loading, you’ll improve website performance and enhance user experience, resulting in increased engagement and higher conversion rates.  

Curious about the impact of lazy loading on your website’s loading times? Visit Catchpoint WebPageTest and run a test for free.

This is some text inside of a div block.

You might also like

Blog post

Performing for the holidays: Look beyond uptime for season sales success

Blog post

Catch frustration before it costs you: New tools for a better user experience

Blog post

From refresh to results: the metrics that shaped Election Day 2024 coverage