Image optimization and Hugo

[Updated on December 2021]

In this post, I will show you one more way to improve page load speed - optimize images.

The most common image formats on the web today are JPG, PNG and GIF and each suited for different use cases. There is another image format called WebP that combines the best of these image formats.
It’s up to 70% smaller in size and supported by 95.7% of the modern browsers (December 2021).

I converted all the png’s I have on this site to WebP and on average new images were 52% smaller (69% max and 26% min).
And those png images were already optimized with pngout (great macOS UI here).

Random screenshot would be 4x smaller:

-rw-r--r--@  1 stas  staff   402K Mar 28 15:40 original screenshot.png
-rw-r--r--@  1 stas  staff   100K Mar 28 15:41 converted to.webp
-rw-r--r--@  1 stas  staff   225K Mar 28 15:42 optimized with pngout.png
The only problem is that WebP still not supported in Safari (and iOS).

[Update]: Starting from macOS BigSur it is now supported.

Workaround is the following fallback idea:

<picture>
    <source srcset="image.webp" type="image/webp">
    <source srcset="image.jpg" type="image/jpeg">
    <img src="image.jpg">
</picture>

To simplify the workflow in Hugo we can use shortcodes:

  1. Create the new shortcode layouts/shortcodes/image.html with the content:
{{ if .IsNamedParams }}
<picture>
  <source srcset="{{.Get "src" }}.webp" alt="{{.Get "alt" }}" title="{{.Get "alt" }}" type="image/webp">
  <source srcset="{{.Get "src" }}.png" alt="{{.Get "alt" }}" title="{{.Get "alt" }}" type="image/png"> 
  <img src="{{.Get "src" }}.png" alt="{{.Get "alt" }}">
</picture>
{{ end }}
  1. Then replace the markdown image formatting
![GitHub Logo](/images/logo.png)

with:

{{< image src="/images/logo" alt="GitHub Logo" >}}
  1. Convert images to webp with command line tool cwebp (documentation).
    Example of the shell script (placed in scripts blog root folder):
#!/usr/bin/env bash
SCRIPTPATH="$( cd "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
cd "$SCRIPTPATH"/../static/images
ls | grep png | sed 's/.png//' | while read fileName; do 
    if [ ! -f "$fileName".webp ]; then 
        cwebp "$fileName".png -o "$fileName".webp
    fi
done

webp on macOS installs with brew install cweb

   

   

   

Useful links: