Image optimization using @11ty/eleventy-img

Low level utility to perform build-time image transformations for both vector and raster images.
Output multiple sizes, save multiple formats, cache remote images locally. Uses the sharp image processor.


Image - Eleventy Documentation

Features #

Using Shortcode #

The easiest way to use eleventy-img is to create a shortcode to use within content.

I used the image shortcode to implement the banner image below the blog article title.

Shortcode Example #

eleventy.config.js

module.exports = function(eleventyConfig) {
  eleventyConfig.addShortcode("image", async function(src, alt, sizes) {
    let metadata = await Image(src, {
      widths: [300, 600],
      formats: ["avif", "jpeg"]
    });
    let imageAttributes = {
      alt,
      sizes,
      loading: "lazy",
      decoding: "async",
    };
    return Image.generateHTML(metadata, imageAttributes);
  });
};
    { % image "cat.jpg", "photo of my tabby cat" %}

Browser Based Lazy Loading #

The generated picture element contains loading="lazy" decoding="async" to img utilizing browser based lazy loading.

The loading attribute on an img element (or the loading attribute on an iframe) can be used to instruct the browser to defer loading of images/iframes that are off-screen until the user scrolls near them.


Lazy loading - Web performance | MDN

Source Code #

The source for my 11ty blog is available on github.

11ty-equk