如何给 img 标签自动添加 loading="lazy" 属性?

解读

在国内前端工程化面试中,性能优化是高频考点,而“图片懒加载”又是性能优化的必答题。面试官抛出此题,表面看是“改一段 HTML”,实则考察三点:

  1. 你是否理解 Gulp 的流式处理哲学(文件 → 转换 → 文件),而不是“写个脚本跑一遍”;
  2. 你是否熟悉 Vinyl 文件对象 与 through2 流 的配合,能在不落地磁盘的前提下完成 AST 级改写;
  3. 你是否具备 工程化安全意识,即改动必须可回滚、可白名单、可兼容旧浏览器,而不是粗暴字符串替换。
    因此,回答时要体现“流 → AST → 属性注入 → 条件判断 → 源映射”的完整闭环,才能拿到 高分档。

知识点

  1. Vinyl:Gulp 的虚拟文件,内容可能是 Buffer 或 Stream,必须通过 through2 转成可编辑的 Buffer。
  2. AST 解析:HTML 不能用正则硬刚,必须用 posthtml 或 htmlparser2 生成 AST,保证标签闭合、属性大小写、单双引号等边界场景不翻车。
  3. 条件注入:仅对 无 loading 属性 且 宽高大于 0 的 <img> 节点追加,避免把占位图或 1×1 像素追踪也懒加载。
  4. 源映射:使用 gulp-sourcemaps,让构建后行号可调试,体现 大厂规范。
  5. 缓存与增量:配合 gulp-cache 与 gulp-newer,10 万级图片的官网也能秒级增量构建,符合国内 CI 流水线 要求。
  6. 降级方案:面试必须补充“如果仍需兼容 IE11”,可输出 data-src + 手写 IntersectionObserver Polyfill,展示 兼容广度。

答案

// gulpfile.esm.js  (Node ≥14,国内团队已普遍使用 ESM)
import gulp from 'gulp';
import through2 from 'through2';
import posthtml from 'posthtml';
import { readFileSync } from 'fs';
import path from 'path';

const posthtmlLazy = () => {
  return through2.obj(function(vinyl, enc, cb) {
    if (vinyl.isNull()) return cb(null, vinyl);
    if (vinyl.isStream()) return cb(new Error('Streaming not supported'));

    const html = vinyl.contents.toString();
    const result = posthtml([
      tree => {
        tree.match({ tag: 'img' }, node => {
          // 仅当节点没有 loading 属性时才注入
          if (!node.attrs || node.attrs.loading) return node;
          // 可扩展:读取宽高,小于 5 KB 的 icon 图跳过
          node.attrs.loading = 'lazy';
          return node;
        });
        return tree;
      }
    ]).process(html, { sync: true });

    vinyl.contents = Buffer.from(result.html);
    cb(null, vinyl);
  });
};

export const html = () =>
  gulp.src('src/**/*.html')
      .pipe(posthtmlLazy())          // 核心转换
      .pipe(gulp.dest('dist'));

export default gulp.series(html);

关键点说明:

  • 使用 posthtml 而非正则,100% 避免 img 写在注释或字符串里被误杀。
  • 通过 through2 把转换封装成 纯流插件,可直接复用于其他任务。
  • 若公司使用 TypeScript 开发,可再包一层 gulp-plumber 捕获语法树错误,保证 watch 任务不崩。
  • 上线前再加 gulp-htmlmin 压缩,懒加载属性仍被保留,符合国内 CDN 边缘缓存规范。

拓展思考

  1. 服务端渲染(SSR)场景:若团队采用 Next.js 或 Nuxt,构建时已经无静态 HTML,此时应把上述逻辑封装成 Webpack loader 或 Vite 插件,并在面试中回答“Gulp 与 Webpack 职责分工”:Gulp 负责 遗留项目 或 多包异构仓库,新子项目统一 Vite。
  2. 自动计算 sizes 属性:可继续用 posthtml 遍历 <img>,若发现同一目录存在 *.jpg 与 *.webp,自动追加 <picture> 与 type="image/webp",实现 “懒加载 + 现代格式” 双优化,展示你对 前沿性能方案 的掌握。
  3. 灰度与回滚:在 CI 中注入 <!-- gulp-lazy-hash: 7f83b --> 注释,上线后如监控到 CLS 抖动,可快速根据 hash 定位版本并回滚,体现 可观测性 思维。
  4. 低代码平台:国内不少金融、政务项目用 低代码拖拽 生成 HTML,此时把插件封装成 独立 npm 包 并发布到公司私有仓库,让运营人员“零感知”接入懒加载,可成为面试中的 加分故事。