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

如何为gatsby-source-wordpress的所有内联图片默认设置loading: lazy属性

解决方案

针对你当前的场景,有两种可行的配置方式:

方法1:替换原始渲染方式,批量修改图片属性

你当前使用dangerouslySetInnerHTML直接渲染原始HTML,无法直接修改内部元素属性,可替换为html-react-parser实现元素自定义处理,不仅可以统一加懒加载属性,还可以配合gatsby-plugin-image实现更多图片优化:

  • 首先安装依赖:
npm install html-react-parser
  • 组件内渲染代码修改为:
import parse from 'html-react-parser';
import { GatsbyImage } from 'gatsby-plugin-image';

// 渲染逻辑
const renderContent = (content) => {
  return parse(content, {
    replace: (domNode) => {
      if (domNode.name === 'img') {
        // 给原生img添加lazy属性
        domNode.attribs.loading = 'lazy';
        // 如果你需要对接gatsby-plugin-image的优化能力,也可以在这里做属性映射,返回GatsbyImage组件
        // return <GatsbyImage image={xxx} alt={domNode.attribs.alt} loading="lazy" />
      }
    }
  })
}

// 组件内调用
<div>{renderContent(content)}</div>

方法2:在数据拉取阶段批量修改HTML内容

你可以在gatsby-node.js中处理gatsby-source-wordpress拉取到的文章内容,通过正则批量给所有img标签添加loading="lazy"属性,后续直接用dangerouslySetInnerHTML渲染即可:

exports.createResolvers = ({ createResolvers }) => {
  createResolvers({
    WpPost: { // 如果你是自定义文章类型,替换为对应的类型名即可
      processedContent: {
        type: "String",
        resolve: (source) => {
          // 批量给img标签添加loading=lazy属性
          return source.content.replace(/<img /g, '<img loading="lazy" ');
        }
      }
    }
  })
}

修改后你在页面查询文章数据时,查询processedContent字段代替原content字段即可。

注意事项

  • 上述两种方案均兼容你当前使用的Gatsby v3.14、gatsby-source-wordpress v5.14版本
  • 如果你需要开启更深度的图片优化,可以在gatsby-source-wordpress插件配置中开启html.useGatsbyImage配置项,将内容中的图片自动转换为GatsbyImage组件,默认自带懒加载能力,无需额外配置属性

内容的提问来源于stack exchange,提问作者Konstantin Sh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 07:42:01