What's the Best Way to Load Images on Hugo and Add Lazy Loading?

I’m trying to add lazy loading on Hugo. But I’m stuck and I’m requesting some help.

I have the following code to load each blog post on Hugo:

<section class="content-rich-text blog-styling xs-pb-10">
    <div class="blog-styling">
      <div class="content-rich-text-inner prl-5 blog-styling">
        <div class="content-rich-text-leading blog-styling">
          
          {{ .Content }}
        
        </div>
        
        {{ if hugo.Environment | eq "development" }}

        <script type="text/javascript">
          var images = document.getElementsByTagName("img");
          for (var i = 0; i < images.length; i++) {
            images[i].src = images[i].src.replace("/", "/");
          }
        </script>
        
        {{ end }}
      <!-- {{- partial "components/comments.html" . }} -->
    </div>
  </section>

Up to now, the code is working and the images are OK. However, I can’t find the best way to add lazy loading, given that I’m using the following code section to load images from the content:

        <script type="text/javascript">
          var images = document.getElementsByTagName("img");
          for (var i = 0; i < images.length; i++) {
            images[i].src = images[i].src.replace("/", "/");
          }
        </script>

What’s the best solution to load these images while still adding lazy loading?

Is there an alternative to load images efficiently on Hugo?

Any solution is greatly appreciated. Thank you guy.

Add the appropriate attribute to your img elements.

What is your JavaScript code supposed to do? It looks as if it were replacing slashes in the src element by slashes – is that the intention? If so – why?

2 Likes

TLDR: add loading="lazy" and let the browser handle it.

6 Likes

Hugo does offer nearly every tool you could wish for to implement image processing. And it also allows you to include JavaScript libraries for sophisticated lazy loading.

But It does not offer a simple general solution because there isn’t one. To process images and to deliver them efficiently is complicated.

The simplest good solution is the one @frjo mentioned. Don’t use any additional JavaScript, just add the attribute loading="lazy" to your img tags and provide raster images that are large enough for your layout.

You can overwrite the default Markdown image element directly with a render hook template.

2 Likes

I wrote this module

It’s a wrapper for every Hugo feature that relates to images.

Also uses the lazy sizes library for backwards compatibility and no need to specify image sizes.

You can turn lazy sizes support off if you wish

2 Likes