Lazy loading images in markdown-it

Adding loading="lazy" attribute to images in markdown-it

Use a custom image rule in markdown-it to add lazy loading attribute in image tags:

// initiative markdown-it
let md = require('markdown-it')()

// replace a default image rule
md.renderer.rules.image = function (tokens, idx, options, env, slf) {
  var token = tokens[idx]
  token.attrs[token.attrIndex('alt')][1] = slf.renderInlineAsText(token.children, options, env)
  // this is the line of code responsible for an additional 'loading' attribute
  token.attrSet('loading', 'lazy')
  return slf.renderToken(tokens, idx, options)
}

The img tags will contain loading = "lazy" attribute like this:

<img src="xx" alt="xx" loading="lazy" />

Powered by

Node
Github
Copyright 2019 - present