Created
August 18, 2020 17:34
-
-
Save BenDMyers/e8aa73030a19f3d1d00b44096d3c06cf to your computer and use it in GitHub Desktop.
Add lazy loading to images for markdown-it
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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