Get better web performance with Lazy Loading of Images
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


In this article, lets explore the various ways to do so.
I. The native “loading” attribute :
This new attribute(still experimental as per Mozilla docs MDN) simplifies the task for lazy loading images by only requiring to add loading attribute
on an <img/> element. This eliminates the use of a third party javascript library used specifically for lazy loading.
<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.

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-

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:
Browser starts to load images after they encounter the src tag while parsing the HTML. In order to achieve lazy loading, instead of writing src attribute, we can write data-src and later replace it with src attribute (using javascript) when the image tag is visible inside the viewport which will eventually trigger the browser to download the image.
How to detect viewport entry of images-
- ) 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" />

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" />

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:
After experimenting with all the 3 techniques, it can be safely concluded that Intersection Observer API is your safest bet if performance and browser compatibility is your concern.
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.

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/loadinghttps://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!!