@limetech/lime-elements
Version:
28 lines (27 loc) • 921 B
JavaScript
import { visit } from "unist-util-visit";
/**
* Creates a unified.js plugin that transforms image elements for lazy loading
*
* @param lazyLoadImages - Whether to enable lazy loading for images
* @returns A unified.js plugin function
*/
export function createLazyLoadImagesPlugin(lazyLoadImages = false) {
return () => {
if (!lazyLoadImages) {
return (tree) => tree;
}
return (tree) => {
visit(tree, 'element', (node) => {
if (node.tagName === 'img') {
node.properties = node.properties || {};
node.properties.loading = 'lazy';
if (node.properties.src) {
node.properties['data-src'] = node.properties.src;
node.properties.src = undefined;
}
}
});
return tree;
};
};
}