如何采集子应用加载时间?

解读

在国内微前端落地场景中,子应用加载时间直接决定首屏体验与 SEO 评分,也是面试官区分“只会写 gulpfile”与“能端到端性能治理”的关键分水岭。题目表面问“采集”,实则考察三层能力:

  1. 能在构建阶段植入统计代码而不污染业务;
  2. 能在运行时精确捕捉“资源下载→脚本解析→子应用挂载”三段耗时;
  3. 能把数据回传、聚合、报警,形成 DevOps 闭环。
    Gulp 作为流式构建工具,最适合在“构建时”无痛插入探针,因此答题必须体现“构建层埋点 + 运行时采集 + 监控平台对接”三位一体方案,并给出可落地的 gulp 任务片段。

知识点

  • Vinyl 文件系统:通过 gulp.src / dest 在内存中修改子应用入口 html,无痕注入计时器。
  • Node 流 Transform:利用 through2 在管道中动态追加 <script> 片段,避免手写模板。
  • PerformanceObserver:浏览器原生高阶 API,可精准捕获 resource、largest-contentful-paint、first-input-delay 等指标,比手动 performance.getEntriesByType 更轻量。
  • 微前端钩子:如 qiankun 的 beforeLoad、afterMount,配合 performance.mark/measure 计算“脚本解析→挂载”耗时。
  • 数据回传:在 sendBeacon 不可用时降级为 fetch(keepalive: true),并做采样率控制,防止海量日志打爆网关。
  • Sourcemap 对齐:若子应用开启代码分割,需把 webpackChunkName 一并上报,方便事后按 chunk 维度下钻。
  • 合规与性能:国内需过《个人信息保护规范》,上报字段必须脱敏;同时利用 Gulp 压缩阶段把探针代码做 terser 混淆,减少额外体积。

答案

  1. 构建阶段:在子应用 CI 中新增 gulp inject-probe 任务,利用 through2 向 index.html 注入如下探针(已做 babel 压缩):
const probe = `
<script>
(function(w){
  if(w.__SUB_PROBE__)return;
  w.__SUB_PROBE__=1;
  const mark=(n)=>performance.mark('sub_'+n);
  const measure=(n)=>performance.measure('sub_'+n,'sub_start','sub_'+n);
  mark('start');
  // 资源计时
  const po=new PerformanceObserver((list)=>{
    for(const e of list.getEntries()){
      if(e.name.includes(window.__INJECTED_PUBLIC_PATH__)){
        mark('res_done');measure('res_done');po.disconnect();
      }
    }
  });
  po.observe({type:'resource',buffered:true});
  // 挂载计时
  window.__QIANKUN_MOUNTED__=()=>{mark('mounted');measure('mounted');report();};
  function report(){
    const data={
      res:performance.getEntriesByName('sub_res_done')[0]?.duration||0,
      mount:performance.getEntriesByName('sub_mounted')[0]?.duration||0,
      ver:'__BUILD_TIME__'
    };
    navigator.sendBeacon('/sub-perf',JSON.stringify(data));
  }
})(window);
</script>
  1. 在子应用入口 webpack 配置里把 __INJECTED_PUBLIC_PATH__ 替换成 window.__INJECTED_PUBLIC_PATH__ = window.__INJECTED_PUBLIC_PATH__ || '/child/',确保探针能匹配到真实资源路径。
  2. Gulp 任务片段:
function injectProbe(){
  return src('dist/index.html')
    .pipe(replace('</head>',probe+'</head>'))
    .pipe(replace('__BUILD_TIME__',Date.now().toString(36)))
    .pipe(dest('dist'));
}
exports.default=series(parallel(compileSass,bundleJs),injectProbe);
  1. 运维侧:在 Nginx 增加 /sub-perf 日志格式,通过 Filebeat→Kafka→Flink 实时聚合,配置 Grafana 看板,P95 子应用加载时间 > 2s 触发飞书告警。
  2. 灰度策略:利用 Gulp 环境变量 process.env.CHILD_NAME 做采样,如 Math.random()<0.05 才注入探针,避免全量上报。

拓展思考

  • 多框架场景:若子应用既有 React 也有 Vue,可把探针拆成 base.js + framework.js,通过 Gulp 条件判断注入,减少冗余。
  • SSR 子应用:当子应用采用 Next.js 并开启 SSR 时,需在 Document.getInitialProps 里把 mark('start') 提前到服务端渲染之前,否则统计会丢失 TTFB 段。
  • 跨域隔离:若主应用与子应用不在同域,需设置 Timing-Allow-Origin:*,否则 resource 时长为 0;Gulp 可在构建时自动给静态资源响应头加 Timing-Allow-Origin。
  • Long Task 打断:国内低端安卓机常出现 >50ms 长任务,可在探针里追加 PerformanceObserver({type:'longtask'}),把长任务耗时也上报,用于事后 correlation 分析。
  • 构建时性能:探针注入后增加 0.8kB,Gulp 可通过 brotli 压缩再降 30%,并配合 Cache-Control: immutable 让探针脚本永久缓存,做到“只增代码,不增流量”。