When I recently launched the new home for my ebooks on The Valley of Code, I realized that the large number of images was impacting the loading time and increasing my hosting bill. Each page was quite long, with some even reaching 10MB in size. To mitigate this issue, I decided to implement lazy loading for the images, meaning that the browser would only load the image when the user scrolled to that particular section.

Implementing lazy loading was a challenge because the content was written in Markdown, and I had no control over the resulting HTML markup. However, I discovered that Hugo provides a way to override how images are rendered.

To implement lazy loading for images in your Hugo website, follow these steps:

  1. Create a new file in your theme’s directory with the path layouts/_default/_markup/render-image.html.
  2. Insert the following content into the newly created file:
<img src="{{ .Destination | safeURL }}" alt="{{ .Text }}" loading="lazy" />

By adding the loading="lazy" attribute to the img tag, you enable the lazy loading functionality for the images rendered by Hugo.

Implementing lazy loading for images in Hugo enhances the user experience by reducing loading times, especially for pages with lengthy content. It’s important to note that lazy loading is a tradeoff, as there might be cases where users don’t scroll to the images, resulting in unnecessary loading delays. However, in most scenarios, a majority of users don’t encounter these images immediately upon page load.

Give this technique a try, and you’ll likely notice an improvement in your website’s performance and reduced hosting costs.