Add lazy loading of images in Jekyll posts

note, November 05, 2023 on Mitja Felicijan's blog

Normally you define images with ![]() in markdown files. But jekyll also provides a way to adding custom attributes to tags with {:attr="value"}.

If you have lots of posts this command will append {:loading="lazy"} to all images in all your markdown files.

![image-title](/path/to/your/image.jpg)

will become

![image-title](/path/to/your/image.jpg){:loading="lazy"}

Shell line bellow. Go into the folder where your posts are (probably _posts).

find . -type f -name "*.md" -exec sed -i -E 's/(\!\[.*\]\((.*?)\))$/\1{:loading="lazy"}/' {} \;

Under the hood this adds loading="lazy" to HTML img nodes.

That is about it.


Posts from blogs I follow around the net