Eleventy: How to add `loading="lazy"` to all images automatically

Created on 4 Aug 2020  路  3Comments  路  Source: 11ty/eleventy

I have a bunch of markdown files where the images involved are almost always written as: ![title](link)

This gets converted to: <img src="link" alt="title">

I want it to become: <img src="link" alt="title" loading="lazy">

Is this possible without modifying each and every markdown image link? This can be solved with shortcodes but that would mean replacing all existing files that I have. This can potentially be extended to adding any attribute and value.

Possible improvement request: Only add loading="lazy" to all <img>s within an <article>.

Other than shortcodes, arve0/markdown-it-attrs is also a potential solution, but it involves updating all markdown links to include { loading="lazy" }

education

All 3 comments

I haven't tried either, but one of these markdown-it plugins might work:

@AjitZero you can add a transform to Eleventy to add this attribute to all images in the HTML.

I currently add this attributes thanks to my configuration for elevent-plugin-images-responsiver.

you can add a transform to Eleventy to add this attribute to all images in the HTML.

That's exactly what I needed!

Simple solution: (for others looking to do something similar)

eleventyConfig.addTransform("addNativeLazyLoading", (content, outputPath) => {
  if (outputPath && outputPath.endsWith(".html")) {
    content = content.replace(/<img/g, `<img loading="lazy"`);
  }
  return content;
});

The obvious issue with this is that it will also add loading="lazy" within code blocks, which can be solved by writing a regex pattern (will do that later).

Thank you @nhoizey @pdehaan

Was this page helpful?
0 / 5 - 0 ratings