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

如何通过Jekyll::Generator拦截生成过程为图片添加loading='lazy'?

在Jekyll中通过Generator为图片添加lazy加载属性(解决冻结字符串错误)

问题出在你使用了gsub!方法——Jekyll在构建流程中会自动冻结页面/文章的content字符串,防止意外的原地修改,而gsub!是原地修改原字符串的方法,直接调用就会触发can't modify frozen string错误。

修复方案

把lazy_load_images方法里的gsub!换成gsub即可。gsub不会修改原字符串,而是返回一个修改后的新字符串,再将这个新字符串赋值给page.content或post.content就完全符合Jekyll的规则。

修改后的完整代码:

module Jekyll
  class LazyLoadImagesGenerator < Jekyll::Generator
    def generate(site)
      site.pages.each do |page|
        page.content = lazy_load_images(page.content)
      end

      site.posts.docs.each do |post|
        next if post.data["layout"] == "none" # 跳过layout为"none"的文章
        post.content = lazy_load_images(post.content)
      end
    end

    def lazy_load_images(content)
      # 使用gsub返回新字符串,避免修改冻结的原字符串
      content.gsub(/(<img[^>]+)(?<!loading="lazy")>/i, '\1 loading="lazy">')
    end
  end
end

额外说明

  • 这个正则表达式会自动跳过已经带有loading="lazy"属性的img标签,不会重复添加。
  • 如果需要排除更多页面/文章,可以在循环中增加自定义判断逻辑(比如通过页面的data属性过滤)。

内容的提问来源于stack exchange,提问作者7fc9ecfc6810c58545e1bc3b556003

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 03:41:02