cri.dev
about posts rss

Lazy loading images in 11ty/eleventy

Published on

Here I want to show how you can create your own 11ty plugin.

Below I’m going to illustrate how to lazy load images using Eleventy plugins.

Concept

The idea is the following:

In your markdown files you can freely use markdown images (via ![alt](img)).

In the generated html files, all your images will have the loading=lazy attribute applied so that the browser will lazy load them.

The plugin

It uses the npm dependency node-html-parser (install it via npm i -D node-html-parser)

The plugin can be easily installed in your .eleventy.js file via

eleventyConfig.addPlugin(lazyImages, {})

The lazyImages function looks like this:


function lazyImages (eleventyConfig, userOptions = {}) {
  const {parse} = require('node-html-parser')

  const options = {
    name: 'lazy-images',
    ...userOptions
  }

  eleventyConfig.addTransform(options.extensions, (content, outputPath) => {
    if (outputPath.endsWith('.html')) {
      const root = parse(content);
      const images = root.querySelectorAll('img');
      images.forEach((img) => {
        img.setAttribute('loading', 'lazy')
      })
      return root.toString()
    }
    return content;
  })
}

In the output HTML files, you’ll find your images with the loading=lazy attribute applied.

Here, have a slice of pizza 🍕