Skip to content

How to lazy load images in Hugo

When I launched the new home for my ebooks at The Valley of Code I didn’t think about my hosting bill, and the impact of loading lots of images for the clients as well.

Since each page is very long (no navigation, that’s the point of them being books rather than articles), one could even be 10MB.

So I decided to fix this problem by lazy loading them, in other words the browser only loads the image when the user scrolls to that image.

It’s a tradeoff, but I’m pretty sure 99% of people that open a page will never even scroll to that image right away.

Problem was.. I no control over the markup! All the content was in Markdown.

But I found out Hugo allows us to override how images are rendered.

Create the file layouts/_default/_markup/render-image.html in your theme with this content:

<img src="{{ .Destination | safeURL }}" alt="{{ .Text }}" loading="lazy" />

This makes the resulting HTML have the loading="lazy" attribute, which lazily loads images.


download all my books for free

  • javascript handbook
  • typescript handbook
  • css handbook
  • node.js handbook
  • astro handbook
  • html handbook
  • next.js pages router handbook
  • alpine.js handbook
  • htmx handbook
  • react handbook
  • sql handbook
  • git cheat sheet
  • laravel handbook
  • express handbook
  • swift handbook
  • go handbook
  • php handbook
  • python handbook
  • cli handbook
  • c handbook

subscribe to my newsletter to get them

Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing flavio@flaviocopes.com. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.

Related posts about :