目录
判断浏览器是否支持loading=“lazy”
if ('loading' in HTMLImageElement.prototype) {
} else {
}
选择性加载 lozad
const useNative = true;
if(!useNative || !'loading' in HTMLImageElement.prototype){
var lozad = require( 'lozad')
}
MarkdownIt加载插件
let observer
import {mavonEditor} from 'mavon-editor'
let md = mavonEditor.getMarkdownIt()
md.use(function lazy_loading_plugin(md, mdOptions) {
let defaultImageRenderer = md.renderer.rules.image;
md.renderer.rules.image = function (tokens, idx, options, env, self) {
let token = tokens[idx];
if (useNative && 'loading' in HTMLImageElement.prototype) {
token.attrSet('loading', 'lazy');
} else {
let aIndex = token.attrIndex('src');
let srcValue = token.attrGet('src');
token.attrPush(['data-src', srcValue]);
token.attrPush(['class', 'lazy']);
token.attrs.splice(aIndex, 1);
}
return defaultImageRenderer(tokens, idx, options, env, self);
};
});
选择性初始化lozad
...
that.$nextTick(function () {
if (!(useNative && 'loading' in HTMLImageElement.prototype)) {
observer = lozad('.lazy', {
rootMargin: '10px 0px',
threshold: 0.1,
enableAutoReload: true,
})
observer.observe();
}
...
图片设置高度
img {
max-width: 100%;
height: auto;
}
参考
ApoorvSaxena/lozad.js
markdown-it-image-lazy-loading
markdown-it-img-lazy