Lazy loading images


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.


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.


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

First, let's download the library source:

cd site/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='' 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='' width='980' height='551'><rect width='100%' height='100%' fill='#4d597f'/></svg>

Now let's url encode it:

The <img> tag becomes:

<img class="lazy" src="data:image/svg+xml," 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.