Lazy Loading (3): JavaScript

Note: this article is published on 05/31/2024.

In this series of articles, we discuss Lazy Loading and related. There is no Lazy Loading Category on this site; we put the articles in the LINQ category because the behavior of Lazy Loading is based on or related to LINQ.

A - Introduction

This article will discuss Lazy Loading for JavaScript and give a demo to demonstrate the Lazy Loading that will enable the images to load as the site visitors scroll down the page decreasing the page load time. The content of the article is

  • A - Introduction
  • B - Lazy Loading for JavaScript
  • C - Demo

B - Lazy Loading for JaveScript

In this article, we will show you some techniques for lazy loading images using JavaScript.

Images are loaded using the <img> tag. The browser uses the src attribute to trigger image load. The images are loaded as soon as the browser receives the src attribute. We specify the image URL in the data-src attribute. This avoids loading all images upfront.

Using JavaScript HTML DOM EventListeners 

To trigger the load of the images, you can use event listeners such as scroll, resize, and Orientation Change. 

  • Scroll: The scroll event is triggered when the webpage is scrolled. 
  • Resize: This occurs when the browser size changes.
  • Orientation Change – The event is triggered when the device’s orientation is changed from portrait to landscape or vice versa.

These three events catch the changes in the screen and specify the number of visible images and trigger them to load. EventListener can be easily added and removed using addEventListener() and removeEventListener().

In our example shown below, the first three pictures are loaded in normal (default, eager loading), while others are loaded by lazy loading.

C - Demo for JavaScript Lazy Loading

The code,

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      img {
        width: 500px;
        height: 350px;
        display: block;
        margin: 10px auto;
      }
    </style>
  </head>
  <body>
    <img src="https://images.unsplash.com/photo-1482784160316-6eb046863ece?ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80" />
    <img src="https://images.unsplash.com/photo-1488441770602-aed21fc49bd5?ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80" />
    <img src="https://images.unsplash.com/photo-1426604966848-d7adac402bff?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjExMDk0fQ&auto=format&fit=crop&w=1050&q=80" />
    <img class="lazy-load" data-src="https://images.unsplash.com/photo-1545105511-839f4a45a030?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80" />
    <img class="lazy-load" data-src="https://images.unsplash.com/photo-1493246507139-91e8fad9978e?ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80" />
    <img class="lazy-load" data-src="https://images.unsplash.com/photo-1473800447596-01729482b8eb?ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80" />
    <img class="lazy-load" data-src="https://images.unsplash.com/photo-1491250974528-9443b2902f18?ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80" />
    <img class="lazy-load" data-src="https://images.unsplash.com/photo-1473800447596-01729482b8eb?ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80" />
    <img class="lazy-load" data-src="https://images.unsplash.com/photo-1500993855538-c6a99f437aa7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80" />
    <img class="lazy-load" data-src="https://images.unsplash.com/photo-1501018313157-78d10f597133?ixlib=rb-1.2.1&auto=format&fit=crop&w=1055&q=80" />
    <script>
      document.addEventListener("DOMContentLoaded", function() {
        let lazyloadImages = document.querySelectorAll("img.lazy-load");
        let lazyloadThrottleTimeout;

        function lazyload() {
          if(lazyloadThrottleTimeout) {
            clearTimeout(lazyloadThrottleTimeout);
          }
          lazyloadThrottleTimeout = setTimeout(function() {
            let 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);
      });
    </script>
  </body>
</html>

Open the HTML page in Google Chrome:

Open the Google Chrome DevTools by Right-Click the browser => Inspect

In DevTools => Click Network in the top tab => Click img in the Element tab

Refresh the page; we can see the first 3 photos with src as attributes:
Will be loaded in DevTools:
Scroll down to show we can see the other Photos are loaded in DevTools:
Right Click Waterfall => Waterfull => Total Duration:
Now we can see the Total Duration for the Photos loading:
 
References