在mavon-edit中实现图片lazyloading

vue 图片加载
创建时间:2021-11-17 01:31:40

目录

判断浏览器是否支持loading=“lazy”

if ('loading' in HTMLImageElement.prototype) { // Browser supports `loading`.. } else { // Fetch and apply a polyfill/JavaScript library // for lazy-loading instead. }

选择性加载 lozad

const useNative = true; if(!useNative || !'loading' in HTMLImageElement.prototype){ // 不启用或不支持,加载lozad 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) { //支持且开启 增加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); }; });

选择性初始化lozad

... //给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