App & Browser Testing Made Easy

Give your users a seamless experience by testing on 3000+ real devices and browsers. Don't compromise with emulators and simulators

Get Started free
Home Guide How to Lazy Load Images in Javascript

How to Lazy Load Images in Javascript

By Alagammai Kannappan, Community Contributor -

Images are vital to websites and applications irrespective of the device that they are accessed. A perfect image is a message half conveyed. Images occupy more than half of the webpage and are the most important asset.  They are added to the website banner, logo, product descriptions, etc. It is critical to load the entire website without compromising quality and content.

What is a Lazy Loading Image?

Lazy Loading images is a technique to load images on a web page only when required. This way can improve the page’s loading time without reducing the page size. 

Users can only view its first fold and associated images when they open a website. The images below the first fold need not be loaded right at the beginning. The Lazy loading images will load images only when they are present within the viewport. 

This is done because the user may navigate to a different page from a particular section on a page. In such cases loading all the images below that fold or section on the webpage unnecessarily consumes loading time.

For instance, Let us take BrowserStack’s image loading technique. 

  • Go to the website www.browserstack.com
  • Right click and select Inspect
  • Click the Network Tab
  • Select Img option and scroll through to see the image request loading with each scroll.

Screenshot 2022 08 09 134547

 As you scroll through, we can see the images loading. We can evaluate a Page’s performance using Google PageSpeed Insight. There is a factor called Passed Audits in the PageSpeed Insights for Images Loading on every Web Page. This audit can be passed only when the lazy loading technique is implemented.

audit

Why Lazy Load Images?

The main idea of Lazy loading images is to improve the website performance and reduce the delivery cost. The term, improved performance refers to reducing the downloads and quicker processing of requests. Faster loading of pages leads to better usability. 

The lazy loading of images reduces the number of bytes transferred, which benefits the total delivery cost.lazyload audit

Techniques for Lazy Loading Images in Javascript

Images on a webpage can be loaded either using <img> tags or CSS background property.

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.

1. Using 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.

document.addEventListener(“scroll”, lazyload);

window.addEventListener(“resize”, lazyload);

window.addEventListener(“orientationChange”, lazyload);

lazy loading images in javascript

EventListener can be easily added and removed using addEventListener() and removeEventListener().

The first image fold must be added upfront for a better experience. The first image fold will have an src attribute, whereas the folds below will later load data-src.

Once you have added these elements it is essential that you test them. Using Percy, one can calculate the height of the page, by scrolling to the end of the page and then taking a screenshot for each screen scrolled.

Try Percy for free

2. Using Intersection Observer API 

The Intersection Observer API asynchronously observes the changes and loads images as the element enters the viewport. The prior approach required us to bind events, consider performance, and build a mechanism to determine if an element was in the viewport or not. This is relatively straightforward, arithmetic is avoided, and excellent performance is provided through the Intersection Observer API.

You can add the observer to every image that will be loaded slowly. Using the isIntersecting property, you can select the URL from the data-src attribute and shift it to the src attribute so that the browser can load the image when the API determines that the element has entered the viewport. Once this is finished, you can take the observer and the lazy class out of the image.


document.addEventListener(“DOMContentLoaded”, function() {

  var lazyloadImages;    

  if (“IntersectionObserver” in window) {

    lazyloadImages = document.querySelectorAll(“.lazy”);

    var imageObserver = new IntersectionObserver(function(entries, observer) {

      entries.forEach(function(entry) {

        if (entry.isIntersecting) {

          var image = entry.target;

          image.src = image.dataset.src;

          image.classList.remove(“lazy”);

          imageObserver.unobserve(image);

        }

      });

    });

Images load faster in Intersection Observers when compared to event listeners. However, some browsers may not support Intersection Observer API and might have to opt for event listeners. 

To know the list of browsers that support Intersection Observer API, refer to caniuse website.caniuse

Difference between Event Listeners and Intersection Observers

Event ListenersIntersection Observers
Manually calculate when an element enters the viewportAsynchronously Observe changes
Required to fire off at even the smallest scroll movementWhen the threshold is reached, or the target element enters the viewport, executes its callback function once.

For most businesses moving online, the need for Lazy Loading Image has peaked. The e-commerce website needs to showcase all its products to the customers without compromising the image quality or the number of images on a page. The Lazy Loading Images technique will boost the e-commerce website’s performance

Image Place Holders

Now that images are lazily loaded, what will appear when the images are still loading? You need to add image placeholders to avoid the emptiness of the webpage. You can either have block colors or low-quality image placeholders. The block colors will be aligned to the image loaded in the place. However, a better option would be to blur or add low quality of the actual image, which will give the user a better idea of what is still loading. 

image placeholder

That said, one should not lazy load all the images on a web page if the page isn’t too long, if there are fewer images on a webpage, or if the images are present close to the viewport. The ability of the user’s browser to execute Javascript is a requirement for lazy loading to work. Although native lazy loading claims to eliminate this reliance, with browser support remaining at or near 70%, JavaScript libraries are still required to deliver the same experience across all browsers.

BrowserStack allows you to seamlessly test your websites and applications on 3000+ devices and browsers. You can test your website from your local, dev, and production environments. 

Try BrowserStack for Free

Tags
Types of Testing Website Testing

Featured Articles

How to Reduce Page Load Time in Javascript

How to resolve JavaScript Cross Browser Compatibility Issues

App & Browser Testing Made Easy

Seamlessly test across 20,000+ real devices with BrowserStack