HUGO

Responsive lazy loaded images

Grab a copy of this awesome library and store it in your assets/js folder.

Step 1
In our head we include the lazyload library. For performance reasons we only load the library when the page contains images.

{{ if or (.Resources.Match "**.jpg") (.Resources.Match "**.png") }}
{{ $lazyload := resources.Get "js/lazyload.js" }}
{{ $lazyload := $lazyload | resources.Minify }}
{{ with $lazyload }}
{{ $secureJS := . | resources.Fingerprint }}
<script type="text/javascript" src="{{ $secureJS.RelPermalink }}" integrity="{{ $secureJS.Data.Integrity }}" crossorigin="anonymous"></script>
{{ end }}
{{ end }}

Step 2
Now it’s time to initialize the lazyload library. In our footer we add the following snippet. Note that we tell lazyLoad that we want elements with the class ‘lazy’ to be lazy loaded.

{{ if or (.Resources.Match "**.jpg") (.Resources.Match "**.png") }}
  <script>
    var lazyLoadInstance = new LazyLoad({
      elements_selector: ".lazy"
    });

  </script>
  {{ end }}

Step 3
In our templates we can now lazyload every image. We leverage Hugo’s awesome build in image features to create two versions of our image.

{{ $alt := .alt }}
{{ if .image }}
  {{ with $.Page.Resources.GetMatch .image }}
    {{ with .  }}
      {{ $src1x := (.Fill "500x620 Center") }}
      {{ $src2x := (.Fill "1000x1240 Center") }}
      <img data-src="{{ $src1x.RelPermalink }}" data-srcset="{{ $src1x.RelPermalink }} 1x, {{ $src2x.RelPermalink }} 2x" alt="{{ $alt }}"
        class="lazy" width="{{$src1x.Width}}" height="{{$src1x.Height}}">
    {{ end }}
  {{ end }}
{{ end }}
4 Likes

It seems 404 for the links.

without the ending dot :slight_smile:

Thanks for pointing it out. Fixt

1 Like

As an alternative, lazysizes is really cool too.

1 Like

Thank you for your tip.

By the way: There is a pretty new HTML lazy loading tag, and the browser support is better than I expected.

Edit: Wow—I just saw that the vanilla lazyload library support native lazy loading. Cool!

3 Likes