How to Implement Lazy Load Images on Your Website

Images play a crucial role in all websites and applications nowadays. From marketing banners to product images and logos, it’s hard to picture a website without them. However, images tend to be quite large in size, which can significantly impact the overall page size.

According to the most recent data from the HTTP Archive, the average size of web pages on desktops is 1046 KB. Images contribute to approximately 889 KB of that size, which accounts for about 80% of the total page size. Considering the importance of images, it is crucial for us to optimize our web pages to ensure fast loading times.

In this guide, we will discuss the concept of lazy loading images. This technique is beneficial as it enhances the page load time and reduces the page size, all while keeping all the images intact on the page.

What is Image Lazy Loading?

Lazy loading is a technique that delays the loading of images (and other resources) until they are actually needed, which is typically when they come into the viewport. This can significantly improve the initial load time of a web page and enhance the user experience.

The term “lazy” in the English language is often associated with avoiding work for as long as possible.

In a similar manner, lazy loading delays the loading of resources on a webpage until they are actually required. Instead of loading these resources immediately when the page loads, as is typically done, they are loaded only when the user needs to access them.

The concept of lazy loading can be applied to almost any resource on a webpage. For instance, in a single page application, it is advisable to not load a JavaScript file until it is actually needed. Similarly, if an image is not immediately necessary, it is better to load it later when it needs to be viewed.

Why go for lazy loading images at all?

Lazy loading images offers several benefits that can enhance both user experience and website performance. Here are three key reasons why you should implement lazy loading for images:

  1. Improved Page Load Speed: Lazy loading defers image loading until needed, reducing initial load times and enhancing website responsiveness. This can also improve search engine rankings.
  2. Reduced Bandwidth Usage: Only loading images when they come into view minimizes data transfer, benefiting users with slow connections or limited data plans by preventing unnecessary downloads.
  3. Enhanced User Experience: Faster load times and efficient data usage create a smoother browsing experience, reducing the likelihood of users abandoning the site due to slow loading.

Which images can be lazy loaded?

Lazy loading is all about delaying the loading of unnecessary content. In the case of images, this means that any image not immediately visible to the user can be loaded lazily.

When the user scrolls down, the image placeholders will gradually appear in the viewport. The images will start loading once they are in view.

You can discover which images are eligible for lazy loading and the amount of data you can save on the first page load by utilizing the Google Lighthouse audit tool. This tool conducts an audit that includes a specific section for offscreen images. Lazy loading is critical not only for good performance, but also to deliver a good user experience.

Lazy loading techniques for images

There are two ways to load images on a webpage – through the <img> tag or the CSS background property. Let’s start by exploring the more commonly used method, the <img> tag, and then we’ll move on to CSS background images.

Lazy loading images in <img> tag

To start, you can prevent the image from loading right away. When an image is loaded using the img tag, the browser looks for the src attribute to initiate the image load. It doesn’t matter if it’s the first or the thousandth image in your HTML code and even if it’s not visible on the screen, once the browser detects the src attribute, it will start loading the image.

To lazy load images, you can place the image URL in a different attribute instead of src. For example, you can use the data-src attribute within the image tag. By leaving src empty, the browser won’t load the image automatically.

<img data-src="https://picsum.photos/200/300" />

Now that we’ve stopped the upfront load, we need to tell the browser when to load the image. For this, we check that as soon as the image (i.e., its placeholder) enters the viewport, we trigger the load. The following steps will enable lazy-loading for the images:

  • Create a new folder to start off with the project.
  • Create an index.html file with the following code.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Lazy Loading Images</title>
    <style>
      img {
  background: #F1F1FA;
  width: 300px;
  height: 250px;
  display: flex;
  margin: 10px auto;
  border: 0;
}
    </style>
</head>
<body>
  <img src="https://cdn.pixabay.com/photo/2020/04/06/12/37/daisy-5009532_1280.jpg" />
  <img src="https://cdn.pixabay.com/photo/2015/01/30/10/54/cup-617422_960_720.jpg" />
  <img src="https://randompicturegenerator.com/img/picture-generator/57e0d643425aa814f1dc8460962e33791c3ad6e04e507440712f7bd5904bc1_640.jpg" />
  <img class="lazy" data-src="https://randompicturegenerator.com/img/picture-generator/57e1d1454a57b10ff3d8992cc12c30771037dbf85254784a702879d49f4f_640.jpg" />
  <img class="lazy" data-src="https://randompicturegenerator.com/img/picture-generator/57e0dd414a56a414f1dc8460962e33791c3ad6e04e50744172297bd49749cc_640.jpg" />
  <img class="lazy" data-src="https://randompicturegenerator.com/img/picture-generator/55e9dd4b4a57a414f1dc8460962e33791c3ad6e04e507440762e79d7944ecd_640.jpg" />
  <img class="lazy" data-src="https://randompicturegenerator.com/img/picture-generator/57e9dc434956ab14f1dc8460962e33791c3ad6e04e507440772872dc9244cc_640.jpg" />
  <img class="lazy" data-src="https://randompicturegenerator.com/img/picture-generator/54e3d1474b57ac14f1dc8460962e33791c3ad6e04e507441722a72dc954ac3_640.jpg" />
  <img class="lazy" data-src="https://randompicturegenerator.com/img/picture-generator/54e3d5434b56b10ff3d8992cc12c30771037dbf85254794e722a7dd2954f_640.jpg" />
  <img class="lazy" data-src="https://randompicturegenerator.com/img/picture-generator/57e8d24b4c53b10ff3d8992cc12c30771037dbf85254794e732879d1964a_640.jpg" />
  
  <script src="lazyload.js"></script>
</body>
</html>
  • Create a lazyload.js file and add the following lines of code into it. Here we use event listeners on the scrollresize, and orientationChange events in the browser.
document.addEventListener("DOMContentLoaded", function() {
  var lazyloadImages = document.querySelectorAll("img.lazy");    
  var lazyloadThrottleTimeout;
  
  function lazyload () {
    if(lazyloadThrottleTimeout) {
      clearTimeout(lazyloadThrottleTimeout);
    }    
    
    lazyloadThrottleTimeout = setTimeout(function() {
        var scrollTop = window.pageYOffset;
        lazyloadImages.forEach(function(img) {
            if(img.offsetTop < (window.innerHeight + scrollTop)) {
              img.src = img.dataset.src;
              img.classList.remove('lazy');
            }
        });
        if(lazyloadImages.length == 0) { 
          document.removeEventListener("scroll", lazyload);
          window.removeEventListener("resize", lazyload);
          window.removeEventListener("orientationChange", lazyload);
        }
    }, 20);
  }
  
  document.addEventListener("scroll", lazyload);
  window.addEventListener("resize", lazyload);
  window.addEventListener("orientationChange", lazyload);
});
  • That’s it! Save the files and open it up in your web browser. Here’s a working model of the code give above:

If you take a look, the initial three images in the given example are loaded right away. The URL is directly present in the src attribute instead of the data-src attribute. This is crucial to ensure a positive user experience.

As these images are positioned at the top of the page, it is important to make them visible as quickly as possible. There is no need to wait for an event or JavaScript execution to load them.

Native Lazy Loading

Since the Chrome 76 update onwards, all chromium-based browsers like Micrisoft Edge, Arc, Safari and Firefox support native lazy loading by default. You can check the current status of browser support for lazy loading at caniuse.com.

With the introduction of browser-side support, developers can now easily enable lazy loading on their websites by simply adding a loading attribute when embedding images. So the code would now look something like this:

<img src="example.jpg" loading="lazy" alt="..." />

Lazy Loading CSS Background Images

After inserting <img /> tags, background images are the most common method to display images on a webpage. When it comes to <img /> tags, the browser follows a simple approach – if the image URL is available, it loads the image.

However, loading CSS background images is a bit more complicated. The browser first needs to construct the DOM (Document Object Model) tree and the CSSOM (CSS Object Model) tree to determine if the CSS style should be applied to a DOM node in the current document.

If the CSS rule for the background image doesn’t apply to any element in the document, the browser won’t load the background image. But if the CSS rule is relevant to an element in the current document, the browser will load the image.

Although this process may seem intricate initially, it is the foundation for lazy loading background images. In essence, we deceive the browser into delaying the application of the background image CSS property to an element until that element is within the viewport.

Check out this functional example that demonstrates lazy loading a CSS background image:

Final takeaways for lazy loading images

In conclusion, lazy loading images is crucial for optimizing web performance and enhancing user experience. By delaying image loading until necessary, websites can reduce initial load times and bandwidth usage. This improves page speed and ensures quicker content access for users.

Implementing lazy loading is straightforward and results in better performance metrics and a smoother user experience.

Leave a Comment

Share this