if ('loading' in HTMLImageElement.prototype) {
// Browser supports `loading`..
} else {
// Fetch and apply a polyfill/JavaScript library
// for lazy-loading instead.
}
const useNative = true;
if(!useNative || !'loading' in HTMLImageElement.prototype){
// 不启用或不支持,加载lozad
var lozad = require( 'lozad')
}
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) {
//支持且开启 增加loading="lazy"
token.attrSet('loading', 'lazy');
} else {
//不支持
let aIndex = token.attrIndex('src');
let srcValue = token.attrGet('src');
token.attrPush(['data-src', srcValue]);
//设置class = lazy
token.attrPush(['class', 'lazy']);
// 移除 属性src
token.attrs.splice(aIndex, 1);
}
return defaultImageRenderer(tokens, idx, options, env, self);
};
});
...
//给mavonEditor组件设置内容后
that.$nextTick(function () {
if (!(useNative && 'loading' in HTMLImageElement.prototype)) {
observer = lozad('.lazy', {
rootMargin: '10px 0px', // syntax similar to that of CSS Margin
threshold: 0.1, // ratio of element convergence
enableAutoReload: true, // it will reload the new image when validating attributes changes
})
observer.observe();
}
...
img {
max-width: 100%;
height: auto;
}
ApoorvSaxena/lozad.js
markdown-it-image-lazy-loading
markdown-it-img-lazy