Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Hugo lazy image loading

I presume the images are bundled as post resources in the ./images/ folder.

It creates a new version at 5% of its original quality that is fetched in the initial page load. When and if the original image is loaded by the browser it will replace the low quality one.

{{< lazyimg "images/1.jpeg" >}} {{< lazyimg "images/1.jpeg" "caption" >}}

//put it in layouts/shortcodes/lazyimg.html
{{ $filename := .Get 0}}
{{ $original := .Page.Resources.GetMatch (printf "*%s" $filename) }}
{{ $text := .Get 1 }}
{{ if eq $original nil }}
{{ errorf "cannot find file: %s" $filename }}
{{ end}}
{{ if ne $original.ResourceType "image" }}
{{ errorf "file %s is not an image" $filename }}
{{ end }}
{{ $thumb := ($original.Resize (printf "%dx %s" $original.Width "q3")).RelPermalink }}
<figure>
<img style="max-width: 100%; height: auto;" src="{{ $thumb }}" width="{{ $original.Width }}" height="{{ $original.Height }}" alt="{{ default $text "image" }}" data-src="{{$original.RelPermalink}}" class="lazy" />
{{with $text }}
<figcaption>{{ . }}</figcaption>
{{end}}
</figure>
window.addEventListener('load', function () {
document.querySelectorAll('img.lazy').forEach( image => {
if ( ! image.hasAttribute("data-src")) {
return;
}
const original = image.getAttribute("data-src");
fetch(original)
.then(function (response) {
if (response && response.status == 200){
image.setAttribute("src", original)
}
})
.catch(function(err) {
console.error('lazy error: ', err);
});
}); //image
}) //query
); //listener
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.