A Hugo shortcode using the HTML picture element to enable different formats for the same image
4 minute read
A while ago I published this post about a better figure shortcode for Hugo that enabled lazy loading. Today, I bring you yet another update on the same shortcode. This time around, the focus is on leveraging the HTML picture element, which enables alternative versions of the same image in different formats, leaving the browser to decide which one to use. You can serve the same image in, for instance, JPEG-XL and plain old JPEG at the same time. The browser will read the tag, and select the appropriate image depending on its capabilities. If you use a JPEG-XL-capable browser (Thorium, Pale Moon, Basilisk, Waterfox, LibreWolf, Firefox Nightly), you will be served the smaller JPEG-XL version, otherwise you will get the plain JPEG version.
Here is how to use the shortcode in your Hugo posts and pages:
The above snippet results in the following, once rendered. You should either see “Your browser does not support JPEG-XL” in black, or “Your browser supports JPEG-XL” in green:
You can include up to four sources (src1, src2, etc.), with their corresponding types. Here is the Hugo shortcode file. You need to save it in the file themes/[themename]/layouts/shortcodes/fig.html.