Skip to content

Instantly share code, notes, and snippets.

@BenDMyers
Created August 18, 2020 17:34
Show Gist options
  • Save BenDMyers/e8aa73030a19f3d1d00b44096d3c06cf to your computer and use it in GitHub Desktop.
Save BenDMyers/e8aa73030a19f3d1d00b44096d3c06cf to your computer and use it in GitHub Desktop.
Add lazy loading to images for markdown-it
const FIGURE_WITH_LAZY = /<img\s+.*lazy=.*>/g;
const addLazy = (token) => {
if (token.type === 'image') {
if (!token.attrs) {
token.attrs = [];
}
token.attrs.push(['loading', 'lazy']);
} else if (
token.type === 'html_block' &&
token.content &&
token.content.startsWith('<figure>') &&
!token.content.match(FIGURE_WITH_LAZY)
) {
token.content = token.content.replace('<img ', '<img loading="lazy"');
} else if (token.children) {
token.children.forEach(addLazy);
}
}
module.exports = state => state.tokens.forEach(addLazy);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment