You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TinyMCE编辑器图片懒加载:替换src为1px.png并设置data-src

实现TinyMCE插入图片时替换src并设置懒加载属性

可以通过TinyMCE的setup配置项监听图片插入事件,修改生成的<img>标签属性,具体实现如下:

方法一:监听图片插入事件修改DOM

在TinyMCE初始化代码中添加setup回调,捕获图片插入动作后直接修改标签属性:

tinymce.init({
  selector: '#your-editor-id',
  // 保留你原有的其他配置
  setup: function(editor) {
    // 监听图片插入事件
    editor.on('AddImage', function(e) {
      const imgElement = e.element;
      // 保存原图片地址到data-src
      const originalSrc = imgElement.getAttribute('src');
      imgElement.setAttribute('data-src', originalSrc);
      // 替换src为占位图
      imgElement.setAttribute('src', '/assets/img/1px.png');
      // 确保添加lazyload类
      imgElement.classList.add('lazyload');
      // 自动获取原图片宽高(如果需要固定值可直接替换为数字)
      const tempImg = new Image();
      tempImg.src = originalSrc;
      tempImg.onload = function() {
        imgElement.setAttribute('width', tempImg.naturalWidth);
        imgElement.setAttribute('height', tempImg.naturalHeight);
      };
    });
  }
});

方法二:上传图片时直接返回处理后的标签

如果是本地上传图片的场景,配合images_upload_handler在上传完成后直接返回预设好的img标签结构:

tinymce.init({
  selector: '#your-editor-id',
  images_upload_handler: function(blobInfo, success, failure) {
    // 这里替换成你的实际上传逻辑,获取上传后的图片地址
    const uploadedImgUrl = blobInfo.blobUri(); 
    // 直接返回处理好的img标签
    success(`<img src="/assets/img/1px.png" data-src="${uploadedImgUrl}" class="img-fluid lazyload" width="600" height="254" alt="" />`);
  },
  // 其他原有配置
});

注意事项

  • 如果编辑器已有自动添加img-fluid类的配置,无需重复设置,class属性会自动合并
  • 自动获取宽高的方式需要原图片加载完成,若图片加载慢可能存在延迟,固定宽高可直接写死数值

内容的提问来源于stack exchange,提问作者Sam Mah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 03:35:24