technonaturalist

image link to hive image link to ko-fi

hugo notes: selective lazy loading

posted on: Wednesday, 22 January 2025 @ 10:32am in
tagged

In which I flip normal behaviour and make lazy loading images the default and eager loading the thing you have to do unless it’s the first item in a list.

The nonsense I get up to when deciding to try to make everything green on Pagespeed.

I should also point out I have no idea if I’m doing things correctly or not, this is very much a hackjob.

Here I check to see if I wrote loading= when calling the figure shortcode from index.md like so:

in index.md

{{< figure alt="describe your images better than I do" loading="eager" src="image.ext" >}}

If I did, add loading="[whatever was entered in the figure shortcode which should be "eager" otherwise it won't do the thing anyway]", otherwise load lazily.

in layouts/shortcodes/figure.html

/* [truncated] */
	<img
		/* [truncated] */
        {{ if .Get "loading" }}
            {{ with .Get "loading" | plainify }}loading="{{ . }}"{{ end }}
        {{ else }}
            loading="lazy"
        {{ end }}
        /* [truncated] */
    />
/* [truncated] */
I copied and modified a pre-2024 update of this drop in replacement figure code with srcset and modified it to add watermarking and the above lazy loading

On lists such as the taxonomy pages (I use layouts/_default/list.html) or content type specific pages (the art grid uses layouts/art/list.html and the blogroll uses layouts/blog/list.html) I need the first item in the list to load normally and everything below to load lazily. This works fine on the taxonomy pages, the blogroll and small screens as the second item is usually below the fold or slightly poking above it but Pagespeed complains on larger screen/window sizes as the first 9-16 items are above the fold in the art grid.

I failed at finding an explanation about why this works, there was just a “this should work” with the {{ range ... }} line posted by people who know what they’re doing in their response to people asking for help to do similar things on the hugo forums.

in list.html

/* [truncated] */
        {{ $paginate := .Paginate (.Pages) }}
        {{ range $lazy, $paginate := where $.Paginator.Pages "Params.hidden" "ne" "true" }}
	        /* [truncated] */
			<a href="{{ .RelPermalink }}">
				<img 
					/* [truncated] */
					{{ if $lazy }}loading="lazy"{{ end }} 
					/* [truncated] */ 
				/>
			</a>
            /* [truncated] */

It does work, and I have yet to look into why. At this stage I noted that it seems to add an index number to all the items starting from 0 and is triggering on not-0.