Deep dive into lazy loading images 🖼 
Tags: javascript, lazyload, webdev, webperf
Published: 2020-05-30 16:16:27

## The first question is... why?

In the current web app world saving time and network when a user enters into our webpage means a higher chance of increasing engagement and a big opportunity to have a better user experience. Trust me when I say that in the most of the cases we are wasting a bunch of resources when our user loads a webpage. Resources like, for example network bandwidth.

There's no need to be an expert to realise that if one of the biggest problems in web development is wasting resources the solution could be stopping our user mobiles and computers from wasting them, right?

## Don't load more than what you need

This is a concept that not only come from web development but from game development and in this field they call it **Viewing-frustum culling** which, according to wikipedia, is:

> the process of removing objects that lie completely outside the viewing frustum from the rendering process. Rendering these objects would be a waste of time since they are not directly visible.

if we translate this sentence to the web development environment we could see that our viewing frustum is the above-the-fold of our webpage.

![Imgur](https://i.imgur.com/ObnLmWz.png)

## Why in my opinion native lazy-loading is not an option

Starting from chrome 76 you are able to use the loading attribute to lazy-load resources without the need to write custom lazy-loading code or use a separate JavaScript library. This was my approach the first time that I implemented an image lazy load strategy on a site but after implementing the code.... nothing was happening. Why?

In order to understand better what was happening I decided to deep dive into chromium code and understand better how chromium engineers where implementing their lazy load solution in order to understand what I was doing wrong.

### How does native lazy load works?

The browser will call the next function in order to initialise image monitoring for lazy load [check the code here](https://github.com/chromium/chromium/blob/d1f1b29e2ea972f93a5007aefc7ad911931c8ab6/third_party/blink/renderer/core/loader/lazy_image_helper.cc#L77):

```C++
void LazyImageHelper::StartMonitoring(blink::Element* element) {
  Document* document = GetRootDocumentOrNull(element);
  if (!document)
    return;
	
  // Getting messages in order to perform console.log operations latter if an attribute is not ok.
  using DeferralMessage = LazyLoadImageObserver::DeferralMessage;
  auto deferral_message = DeferralMessage::kNone;
  if (auto* html_image = ToHTMLImageElementOrNull(element)) {
    // Get loading att value, it can be eager, lazy auto or nothing.
    LoadingAttrValue loading_attr = GetLoadingAttrValue(*html_image);
    DCHECK_NE(loading_attr, LoadingAttrValue::kEager);
    if (loading_attr == LoadingAttrValue::kAuto) {
      deferral_message = DeferralMessage::kLoadEventsDeferred;
    } else if (!IsDimensionAbsoluteLarge(*html_image)) {
      DCHECK_EQ(loading_attr, LoadingAttrValue::kLazy);
      deferral_message = DeferralMessage::kMissingDimensionForLazy;
    }
  }

  // Here is where all start: Call the lazy load image observer and start monitoring
  document->EnsureLazyLoadImageObserver().StartMonitoringNearViewport(
      document, element, deferral_message);
}

```

[This code snippet](https://github.com/endlessm/chromium-browser/blob/7c4c6df2a8f8f76fb570d8f6a85b120c0c168c38/third_party/blink/renderer/core/html/lazy_load_image_observer.cc#L172) lead to the `StartMonitoringNearViewport` function which does the next:

```C++
void LazyLoadImageObserver::StartMonitoringNearViewport(
    Document* root_document,
    Element* element,
    DeferralMessage deferral_message) {
  DCHECK(RuntimeEnabledFeatures::LazyImageLoadingEnabled());

  if (!lazy_load_intersection_observer_) { // 1
    lazy_load_intersection_observer_ = IntersectionObserver::Create(
        {Length::Fixed(
            GetLazyImageLoadingViewportDistanceThresholdPx(*root_document))}, // 2
        {std::numeric_limits<float>::min()}, root_document,
        WTF::BindRepeating(&LazyLoadImageObserver::LoadIfNearViewport, // 3
                           WrapWeakPersistent(this)));
  }

```

In order to follow the flow I've put numbers on some lines that I'll explain below.

**What does this code exactly do?**

1 - They check if an intersection observer has been created before, otherwise they create it.

Don't you see? They use the **same implementation** on lazy loading images **natively** **as** with a javascript **library** but using low-level intersection observer API, isn't it amazing? 🙂

2 - Calling `GetLazyLoadImageLoadingViewportDistanceThresholdPX` : this function will get the needed threshold to load images based on the network that you are using.

Here you have the code implementation but if you don't care about implementation you can jump directly to the table below for more info about thresholds:

```C++
int GetLazyImageLoadingViewportDistanceThresholdPx(const Document& document) {
  const Settings* settings = document.GetSettings();
  if (!settings)
    return 0;

  switch (GetNetworkStateNotifier().EffectiveType()) {
    case WebEffectiveConnectionType::kTypeUnknown:
      return settings->GetLazyImageLoadingDistanceThresholdPxUnknown();
    case WebEffectiveConnectionType::kTypeOffline:
      return settings->GetLazyImageLoadingDistanceThresholdPxOffline();
    case WebEffectiveConnectionType::kTypeSlow2G:
      return settings->GetLazyImageLoadingDistanceThresholdPxSlow2G();
    case WebEffectiveConnectionType::kType2G:
      return settings->GetLazyImageLoadingDistanceThresholdPx2G();
    case WebEffectiveConnectionType::kType3G:
      return settings->GetLazyImageLoadingDistanceThresholdPx3G();
    case WebEffectiveConnectionType::kType4G:
      return settings->GetLazyImageLoadingDistanceThresholdPx4G();
  }
  NOTREACHED();
  return 0;
}

```

So according to the [native configuration json5](https://github.com/chromium/chromium/blob/ccd149af47315e4c6f2fc45d55be1b271f39062c/third_party/blink/renderer/core/frame/settings.json5#L963) code we can see that regarding on our internet connexion we will have one or another threshold but this threshold will be **always >= 3000px** which honestly is **alot**

| Network | Threshold |
| ------- | --------- |
| Slow 2g | 8000px    |
| 2g      | 6000px    |
| 3g      | 4000px    |
| 4g      | 3000px    |
| Offline | 8000px    |
| Unknown | 5000px    |

3 - And finally, will call the 'callback' function which will do the next ([check full snippet](https://github.com/endlessm/chromium-browser/blob/7c4c6df2a8f8f76fb570d8f6a85b120c0c168c38/third_party/blink/renderer/core/html/lazy_load_image_observer.cc#L215)):

```C++
void LazyLoadImageObserver::LoadIfNearViewport(
    const HeapVector<Member<IntersectionObserverEntry>>& entries) {
  DCHECK(!entries.IsEmpty());

  for (auto entry : entries) {
    Element* element = entry->target();
    auto* image_element = DynamicTo<HTMLImageElement>(element);
    // If the loading_attr is 'lazy' explicitly, we'd better to wait for
    // intersection.
    if (!entry->isIntersecting() && image_element &&
        !EqualIgnoringASCIICase(image_element->FastGetAttribute(html_names::kLoadingAttr), "lazy")) {
      // Fully load the invisible image elements. The elements can be invisible
      // by style such as display:none, visibility: hidden, or hidden via
      // attribute, etc. Style might also not be calculated if the ancestors
      // were invisible.
      const ComputedStyle* style = entry->target()->GetComputedStyle();
      if (!style || style->Visibility() != EVisibility::kVisible ||
          style->Display() == EDisplay::kNone) {
        // Check that style was null because it was not computed since the
        // element was in an invisible subtree.
        DCHECK(style || IsElementInInvisibleSubTree(*element));
        image_element->LoadDeferredImage();
        lazy_load_intersection_observer_->unobserve(element);
      }
    }
    if (!entry->isIntersecting())
      continue;
    if (image_element)
      image_element->LoadDeferredImage();

    // Load the background image if the element has one deferred.
    if (const ComputedStyle* style = element->GetComputedStyle())
      style->LoadDeferredImages(element->GetDocument());

    lazy_load_intersection_observer_->unobserve(element);
  }
}

```

You can check others point of view regarding this topic [here](https://css-tricks.com/native-image-lazy-loading-in-chrome-is-way-too-eager/)

## So you say that I should use a JS library but... which one?

Taking the web.dev article [Lazy Loading Images and Video](https://developers.google.com/web/fundamentals/performance/lazy-loading-guidance/images-and-video) I invested a bit of time into analysing the different options that we have and the pros and cons of some of them.

### Analysing the state of the art

First of all I checked which solutions we currently have on the market based on web.dev recommendations, how well maintained and how much popularity they have on the community. 

We have 4 recommendations and all of them rely on IntersectionObserver API to perform their work.

I will analyse them using five metrics:

- Stars
- Releases
- Public repos using it
- Contributors
- Library size
- NPM Download trend

**Github**

| Library name                                       | ⭐️ Stars | 🚀 Releases | 📦 Used by | 👥 Contributors | 🏋🏽‍♂️ Size                                                   |
| -------------------------------------------------- | ------- | ---------- | --------- | -------------- | ---------------------------------------------------------- |
| [Lozad](https://github.com/ApoorvSaxena/lozad.js)  | 6.2k    | 17         | 1.5k      | 31             | [1kb](https://bundlephobia.com/result?p=lozad@1.14.0)      |
| [Blazy](https://github.com/dinbror/blazy)          | 2.6k    | 19         | 541       | 3              | [1.9kb](https://bundlephobia.com/result?p=blazy@1.8.2)     |
| [Yall](https://github.com/malchata/yall.js/)       | 1k      | 13         | 69        | 13             | [1kb](https://bundlephobia.com/result?p=blazy@1.8.2)       |
| [Lazy Sizes](https://github.com/aFarkas/lazysizes) | 13.3k   | 100        | 11.2k     | 38             | [3.3kb](https://bundlephobia.com/result?p=lazysizes@5.2.0) |


**NPM Trends**

![https://i.imgur.com/9dglETK.png](https://i.imgur.com/9dglETK.png)

**Conclusion**

It seems that lazysizes is the most community supported library, but is also the heaviest so I'm going to select for my tests and benchmarks TWO of the libraries.

- Lazysizes
- Lozad

### Field test

In order to check which library have a better API I decided to perform a small test on a codesandbox site and check how each implementation behave.

**Lozad:**

```jsx
import React, { useEffect } from 'react';
import lozad from 'lozad';

export default ({ src, ...other }) => {
  const { observe } = lozad();

  useEffect(() => {
    observe();
  }, []);

  return <img className="lozad" data-src={src} {...other} />;
};

```

**Lozad** uses a className as an identifier for the library in order to replace the data-src by a real src attribute in order to load the image.

It also uses an observe function in order to observe the element. The observe function is a function that will mark elements as loaded, so multiple calls to that function shouldn't affect performance at all. You can check the code implementation of that function on load.js source code - [here](https://github.com/ApoorvSaxena/lozad.js/blob/master/src/lozad.js#L121).

**LazySizes:**

```jsx
import React from 'react';
import 'lazysizes';
import 'lazysizes/plugins/attrchange/ls.attrchange';

export default ({ src, ...other }) => {
  return <img className="lazyload" data-src={src} {...other} />;
};

```

LazySizes have a similar api to lozad but you don't need to call observe function, it will be called automatically on import. On the other side if you perform data-src changes dynamically you have to add a plugin that will watch the data-src value so if it changes it will re-trigger the image load function.

More info about ls.attrchange [here](https://github.com/aFarkas/lazysizes/tree/gh-pages/plugins/attrchange)

**Summary: The good and the bad**

Lozad **PROS** :+1:

- Lozad is a really tiny library (only 1kb!)
- Lozad is really easy to use and give us autonomy on calling observe and unobserve methods
- It loads only what needs to load with the default threshold (2 images on mobile)
- It is configurable

Lozad **CONS** :-1:

- Running the observable on each component is not something that I like and even is not a problem on performance, I wouldn't like to have a lozad.observe outside the lazy image component definition, the solution must be provided as it is, with no extra work.
- They are not clear on if the library is SEO compliant and this is a problem if you care about SEO - [more info here](https://github.com/aFarkas/lazysizes/issues/436)

LazySizes **PROS** :+1:

- The api is really easy to use
- The community behind is huge
- It is the library recommended by google
- It is fully SEO compliant
- It has the possibility of extending its capacity with plugins [check here](https://github.com/aFarkas/lazysizes/tree/gh-pages/plugins)
- It is also configurable
- It works right out of the box you only need to import the library

LazySizes **CONS** :-1:

- Library size is the triple of lozad
- If you want to configure it you have to put a config object on the window which is not so elegant.

**General tradeoff to consider if you care about SSR**

- We are lazy loading images using a library that is imported and consumed on our bundles, this means that we loose the SSR power on images as this JS code must be loaded in order to show images on first render. But it shouldn't be a problem at least that you have a big amount of JS to load on your bundle.

## Conclusions

In my opinion in this case the community and google have picked the correct library to trust on, lazy sizes have slight differences that give us the balance between size, usability and maintainability.

> My recomendation is give lazysizes an opportunity and test its viability.


__Head Photo by Kate Stone Matheson on Unsplash__