One of the things I try to remember doing is to add loading="lazy" to the images in the main portion of my content. This means images will only load when you scroll them into the viewport—particularly helpful on mobile to keep page loading times down and even save on bandwidth if the user navigates away before getting the bottom of a page.

But like these images, I’m also lazy. 😂 Wouldn’t it be great if I could just mark all images within <main> as loading lazy? Well, thanks to HTML Inspectors, we can!

Just add this to builders/lazy_images.rb:

class Builders::LazyImages < SiteBuilder
  def build
    inspect_html do |document|
      main = document.query_selector('main')
      next unless main

      main.query_selector_all("img").each do |img|
        next if img[:loading]

        img[:loading] = :lazy
      end
    end
  end
end

This will run through all images within<main> and add loading="lazy" if there isn’t a loading attribute already.

How cool is that?!

P. S. If you have a lot of images in <footer>, you should probably mark them too, which you could also do with an Inspector if you want. An exercise left for the reader!