ApliNi / blog

GNU General Public License v3.0
2 stars 0 forks source link

最简单的实现图片懒加载 for marked.js #6

Open ApliNi opened 1 year ago

ApliNi commented 1 year ago

参考资料

loading 属性: https://developer.mozilla.org/zh-CN/docs/Web/Performance/Lazy_loading marked.js 渲染器: https://marked.js.org/using_pro#renderer

懒加载

允许推迟资源加载, 直到标签接近可视范围.

loading 属性

loading="eager"   // (默认) 立即加载
loading="lazy"    // 懒加载

使用方法

<!-- 图片 -->
<img alt="url" src="info" loading="lazy" />

<!-- 嵌入窗口 -->
<iframe src="url" title="..." loading="lazy"></iframe>

在 marked.js 中使用

https://github.com/markedjs/marked/pull/1781

const renderer = {
    // 图片懒加载 `loading="lazy"`
    image(href, title, text){
        if(href === null){return text;}
        let out = '<img src="' + href + '" alt="' + text + '" loading="lazy"';
        if(title){out += ' title="' + title + '"';}
        out += this.options.xhtml ? '/>' : '>';
        return out;
    }
};

marked.use({renderer});

console.log(marked.parse('![test](img)'));