Lazy loading images

Purpose

The blog makes intensive use of images. The more the page grow, the longer it takes to load.
Plus, it gives a disgraceful content reflow effect.

Technique

The widely spread technique is to take the link to the image out of the src attribute, choosing a different attribute name, and putting the link of a placeholder image into the src attribute.

Js library

To simplify the testing, we'll use the yall.js library.

Setup

Let's make some modifications in the html page to test this technique.

First, let's download the library source:

cd site/js
wget https://raw.githubusercontent.com/malchata/yall.js/master/dist/yall.min.js

Then let's try it on a sample page:

Let's add the yalljs source into the header:

<script type="text/javascript" src="/dl/js/yall.min.js" async></script>

and let's call the lib from inside the body:

<script>document.addEventListener("DOMContentLoaded", yall);</script>

Now, for each of the <img> tag, let's replace the src attribute with data-src, and add a lazy class.
For example, this line:

<img src="/dl/img/IMG_20190302_093004455_HDR.jpg" alt="" />

would become:

<img class="lazy" data-src="/dl/img/IMG_20190302_093004455_HDR.jpg" alt="" />

We still need to add a placeholder or else all the images get loaded at the same time, and there would be no use to make this extra effort.

the modified line become:

<img class="lazy" src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 980 551'%3E%3C/svg%3E" data-src="/dl/img/IMG_20190302_093004455_HDR.jpg" alt="" />

Changing the background color

The data image in the src attribute is very small compared to loading a real image.
The only problem is this create a white background placeholder, and it's ugly when using a black background body.

Let's make a SVG image with a #4d597f color:

<svg xmlns='http://www.w3.org/2000/svg' width='980' height='551'><rect width='100%' height='100%' fill='#4d597f'/></svg>

Now let's url encode it:

%3Csvg%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%20width%3D%27551%27%20height%3D%27980%27%3E%3Crect%20width%3D%27100%25%27%20height%3D%27100%25%27%20fill%3D%27%234d597f%27%2F%3E%3C%2Fsvg%3E

The <img> tag becomes:

<img class="lazy" src="data:image/svg+xml,%3Csvg%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%20width%3D%27551%27%20height%3D%27980%27%3E%3Crect%20width%3D%27100%25%27%20height%3D%27100%25%27%20fill%3D%27%234d597f%27%2F%3E%3C%2Fsvg%3E" data-src="/dl/img/IMG_20190302_093004455_HDR.jpg" alt="" />

which is way bigger than the previous white color version. There must be a way to make it smaller, but it's still very lightweight compared to a real picture.