Get better web performance with Lazy Loading of Images

Annesha Kundu
Nov 27, 2020 · 5 min read

As a web developer, web performance optimisation is a key task. At Tokopedia, we take this key task very seriously. Serving our web pages fast is a key aspect in reducing the bounce rate of our customers. Images and how we load those images on the web page is one of the factors that determine the speed of the page. Lazy loading images is one such approach in loading the page fast.

By lazy loading , we mean downloading the images asynchronously only when they become part of viewport. This helps us in shortening the critical rendering path, as only the images which are required for the initial view of the site are downloaded at first go. Rest of them are loaded upon user interaction like user scroll, or carousel click etc.

Below is what it looks like

Image for post
Image for post
By use of lazy loading, we only loaded the first fold images of the viewport in one of our module at Tokopedia, thereby keeping the total image payload near to just 248Kb
Image for post
Image for post
When user further scrolls, the rest of the images are loaded, based upon their viewport entry

In this article, lets explore the various ways to do so.

I. The native “loading” attribute :

<img src=”exampleImage.jpg” alt=”example image” loading=”lazy” />

This attribute can be used also with iframe.

<iframe src=”exampleVideo.html” title=”example video” loading=”lazy” />

Along with “lazy”, there are two other values that can be passed to loading attribute.
1.) auto — default value. Will have no additional effect.
2.) eager — demands immediate loading of images (for eg — can be used for images above the fold).

Pro Tip -> Always set width and height of images, to minimise layout shifts and get better web vital CLS(Cumulative Layout Shift) score.

<img src=”exampleImage.jpg” alt=”example image” width=”200px” height=”200px” loading=”lazy” />

Key findings and web support -
Not all web browsers currently support loading attribute. you can see the browser matrix here.

Image for post
Image for post
Browser that supports lazy loading via attribute

So for lower versions and unsupported browsers, we require polyfills.
Also, we can detect support for “loading” attribute by checking for `loading in HTMLImageElement.prototype` and subsequently use third party JS for non-supported environment (I am using lazysizes.min.js)
Check out the related snippet here-

Image for post
Image for post

While I was trying out, i found even latest chrome as of now lazy loads only those images which are located way down the page.
(Almost 2000px below the viewport). This does not make it very practically useful for all the use cases.
Therefore, lets check out the conventional way of lazy loading:

Have a look at the working code here.

II. Use of data-src instead of src:

How to detect viewport entry of images-

  1. ) By using event listeners -
    We can make use of event listeners like scroll, resize, and orientation. On fire of these events, we can check whether the images now fall inside the viewport or not. The math is done by calculating the current document scroll top, image’s top offset, and window height. If the image becomes part of the viewport then, we attach the image URL to the src attribute from the data-src attribute. Here is the crux of the code required:
<img class="lazy" data-src="https://ecs7-p.tokopedia.net/img/cache/800/VxWOnu/2020/10/2/7c5bcbce-65ee-46b1-8a48-4f05785e0229.jpg?width=500" />
Image for post
Image for post

Note that this procedure is not an optimised one. Scroll event gets triggered
numerously and rapidly. It is recommended to make use of throttle while executing lazy load function for better web performance.

Checkout the CodePen link here.

2.) Using intersection Observer -
This fantastic API does all the above math behind the scene and is rather more performant. As for the implementation, we add the observer to all the images which are going to be lazy-loaded. Whenever our element enters the viewport, Intersection Observer API makes use of isIntersecting property and attaches the URL to the src attribute from the data-src attribute. Following this, the lazy class is removed and downloading is triggered.

<img class="lazy" data-src="https://ecs7-p.tokopedia.net/img/cache/800/VxWOnu/2020/10/2/7c5bcbce-65ee-46b1-8a48-4f05785e0229.jpg?width=500" />
Image for post
Image for post

Note that Intersection Observer too is not supported in all browser versions so we ought to use pollyfill as a fallback. Check out the web support here.

Have a hands-on with the code here.

Conclusion:

We at Tokopedia, at present, make use of the same for lazy loading of images, which help us to achieve 90+ web performance score (Page Speed Insight Score) of our main landing pages.

Image for post
Image for post

For more insights on the topic, do visit the official MDN docs -
https://developer.mozilla.org/en-US/docs/Web/Performance/Lazy_loading
https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/loading

https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

Stay tuned to get a deeper understanding of what made us achieve 90+perf score and till then, Happy Coding!!

Tokopedia Engineering

Story from people who build Tokopedia

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store