Image Optimization Using srcset with a Hugo Shortcode

May 2020 ยท 2 minute read

Hugo Shortcodes to Process Your Images!

We’re all familiar with slow website loads in circumstances where images aren’t optimized (food blog frustrations, anybody?). Fortunately, for those using Hugo as their static site generator, we can use a Hugo Shortcode to generate optimized image sets.

If you are unfamiliar with the srcset attribute, it essentially provides a way for a browser to pick the size of an image that is most appropriate for the browser to display at that time. You can read more about it here.

Google Lighthouse

Lighthouse gives you a score for your website. A good lighthouse score is reflective of a good user experience, plus it helps promote your site in search rankings.

From the Google Lighthouse homepage:

Lighthouse is an open-source, automated tool for improving the quality of web pages. You can run it against any web page, public or requiring authentication. It has audits for performance, accessibility, progressive web apps, SEO and more.

I ran Lighthouse against two webpages I created to showcase the effects of using <img srcset="">, vs. a plain-old <img src="">

Direct Comparison Using srcset

Code

I keep the source code for this blog on Github, and you can find this post and the sub-folders (i.e. example pages linked below) at this link.

Hosted Example Pages

So what is the effect on your performance score if you’re not using the srcset attribute? Let’s look at a real head-to-head comparison between two pages with the same images!

  1. https://blog.concannon.tech/tech-talk/img-srcset/no-srcset

    • does not use the srcset attribute, and uses .jpg files imported from my iPhone 11
  2. https://blog.concannon.tech/tech-talk/img-srcset/srcset

    • uses the srcset attribute to resize images and employ other best practices (like using alt attributes)

Without srcset

Chances are that if you’re not using srcset, the Lighthouse score will be less than 100. Mine was 92 after I cleared the Cloudflare cache for my site, and as high as 99 when the assets were served via Cloudflare’s CDN…

But as you can see from the screenshot below (using srcset, of course!), Lighthouse identified many improvements that I could make related to “properly sized images” and avoiding “enormous network payloads” from the full image downloads.

Google Lighthouse suggestions for improvement include resizing images and avoiding enormous network payloads

Screenshot of the Lighthouse Score for https://blog.concannon.tech/tech-talk/img-srcset/no-srcset/

Using srcset

With the use of srcset, my performance score is 100!

Google Lighthouse Score showing a 100 for Performance

Screenshot of Lighthouse Performance Score of 100 for https://blog.concannon.tech/tech-talk/img-srcset/srcset/