Native image lazy load & define width + height

I was looking around for an easy way to what I was trying to achieve.. but didn’t find it, so I decided to create a pipe (that’s what they are called, right ? :D) on my own.

I was basically trying to achieve two things:

  • Adding html image lazy load which is now supported by majority of browsers
  • Adding image width/height so in case of loading my page won’t jump like crazy

^ these should improve pagespeed rating quite a bit in some cases.

Anyway, this is piece of code which you should put in layouts/_default/_markup/render-image.html, this works for images that have relative path set to folders static or content.

<!-- layouts/_default/_markup/render-image.html -->

{{ $img := "" }}
{{ $source := ( .Destination | safeURL ) }}
{{ $imgPath := add "/content" $source }}
{{ if fileExists $imgPath }}
    {{ $img = imageConfig $imgPath }}
{{ else }}
    {{ $imgPath := add "/static" $source }}
    {{ if fileExists $imgPath }}
        {{ $img = imageConfig $imgPath }}
    {{ end }}
{{ end }}

{{ if $img }}
  <img
  src="{{ $source }}"
  alt="{{ htmlUnescape .Text }}"
  loading="lazy"
  width="{{ $img.Width }}"
  height="{{ $img.Height }}"
  />
{{ end }}

And this is how the generated html code looks like: ><

Note: It is necessary to use css img {height: auto;max-width: 100%} so the images are properly automatically sized on your page afterwards.

powered by Disqus