Grab a copy of this awesome library and store it in your assets/js folder.
- This code is based on using Hugo’s leaf bundles.
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 }}