CTO and co-founder of Signal Sciences. Author and speaker on software engineering, devops, and security.

How to use Data URLs for Image Icons with Hugo

Replace expensive network calls to load image icons with an embedded data URL in your Hugo site

Many times a site needs an image icon. They are commonly used once per page, in the header or footer, are small -- under 128x128 pixels and a few kilobytes. Using a network call, either back to the site, or another site (often a social media site) has a number of problems:

  • loading requires a network round trip which is slow and possibly render blocking
  • can cause the image to flash-in later, which is annoying
  • requires fooling around with cache header settings, and debatable how much caching helps in this case

Instead of a network call consider embedding the image into the page itself using a data url. With no network call, the page loads quickly. True, by having the the image embedded into the page, one loses any cache savings. However the savings is likely to be overstated. Especially for casual sites, like most blogs. Especially when the icon is under a few kilobytes.

In Hugo, the static site generator, making data URLs is easy to do with the partial templates or shortcodes feature. This is similar to techniques to embed SVG icons in Using Font Awesome Icons in Hugo. Here’s the steps this site used to the make the author icon.

Create a file icon.html in the layout/partials folder with the following:

<img width=64 height=64 class="rounded-circle" alt="picture of Your Name"
  src="data:image/jpeg;base64,{{ readFile "icon.jpeg" | base64Encode }}" >

It’s short, but there are a number of details:

  • The readFile function reads files relative to the root directory of your site (where your config file is).
  • The example uses a mime type of image/jpeg , but you can use image/png or any other image format you want.
  • Setting the width and height allows the browser to render the page faster, with less repaints.
  • The alt tag makes your page more accessible
  • The rounded-circle class is from Bootstrap

Then you can use it with:

{{ partial "icon.html" . }}

And that’s it. Enjoy the load-times.

hugo webdev

© 2018 Nick Galbreath