Skip to content

Instantly share code, notes, and snippets.

@bgadrian
Last active May 1, 2020 19:46
Show Gist options
  • Save bgadrian/68ec61ed90d7ebe879bd7f0ce4a2a701 to your computer and use it in GitHub Desktop.
Save bgadrian/68ec61ed90d7ebe879bd7f0ce4a2a701 to your computer and use it in GitHub Desktop.
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
@wisnuwiry
Copy link

execute of template failed: template: shortcodes/lazyimg.html:9:18: executing "shortcodes/lazyimg.html" at <$original.ResourceType>: nil pointer evaluating resource.Resource.ResourceType. Please help

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment