用 Long Animation Frames API 定位重脚本:modern-web-guidance 验收标准与工程实践

原创2026-11-12 10:47:162,202 阅读
文章标签:前端文档AI 技能AI 评测Agent 评测人工智能RAGCLI提示工程

用 Long Animation Frames API 定位重脚本:modern-web-guidance 验收标准与工程实践

本篇以 modern-web-guidance 仓库中「Identify heavy-running JavaScript」指南的验收标准为骨架,讲清两件事:如何用 PerformanceObserver 以 type: 'long-animation-frame' 且 buffered: true 的方式采集长动画帧,以及为什么这里明确禁止引入 Long Animation Frames 的 polyfill。读完你可以把一段可直接上线的采集代码落到自己的页面里,并理解仓库自动评分器是如何逐条校验这两个约束的。

验收标准原文与解读

关联文档 expectations.md 只有两条可判定的要求,但它定义了整篇指南的"及格线":

  • 必须使用 PerformanceObserver,并传入 type: 'long-animation-frame' 与 buffered: true 两个选项;
  • 不得为长动画帧引入任何 polyfill。

这两条看似简单,实际上分别约束了「采集入口是否正确」和「降级策略是否克制」。仓库把这两条写成了机器可执行的断言(见 grader.ts),因此它们不是风格建议,而是必须满足的实现契约。指南正文 guide.md 则解释了背后的动机:重跑的 JavaScript 既可能来自应用自身与框架代码,也可能来自聊天挂件、视频播放器、埋点与营销脚本;而实验室数据只能复现真实用户场景的一小部分,现场(field)数据必须靠轻量 API 采集。

同一目录下的任务描述 task.md 进一步把目标写成一句可执行的需求:为脚本性能增加监控,检测造成帧延迟的慢脚本,并记录过去已经发生的长帧。

为什么选择 Long Animation Frames API

long-animation-frame 条目在动画帧渲染耗时超过 50ms 时触发,条目里带有该帧的时长,以及在这一帧内执行过的脚本列表。相比 JS Self-Profiling API 这类采样剖析方案,LoAF 的运行时开销低得多,适合在真实用户环境常驻开启,这也是指南在「Best Practices」中明确要求优先选择它的原因。

下面是 guide.md 给出的完整采集示例,逻辑覆盖了「跨回调累积」「按来源聚合」「阈值过滤」「按总耗时排序」四个关键点,可直接复制使用:

// Accumulate all script entries across the page lifecycle so no
// data is lost between observer callbacks.
const allScripts = [];

const observer = new PerformanceObserver(list => {
  // Collect all script entries across frames to find the biggest offenders.
  allScripts.push(...list.getEntries().flatMap(entry => entry.scripts));

  // Group by sourceURL so you can identify which scripts contribute
  // the most total time, even if each individual invocation is short.
  const scriptSource = [...new Set(allScripts.map(script => script.sourceURL))];
  const scriptsBySource = scriptSource.map(sourceURL => ([sourceURL,
      allScripts.filter(script => script.sourceURL === sourceURL)
  ]));
  const processedScripts = scriptsBySource.map(([sourceURL, scripts]) => ({
    sourceURL,
    count: scripts.length,
    totalDuration: scripts.reduce((subtotal, script) => subtotal + script.duration, 0)
  }));

  // Only include scripts above a certain threshold to reduce noise.
  const heavyScripts = processedScripts.filter(script => {
    return script.totalDuration > 100;
  });

  // Sort by total duration so the worst offenders appear first,
  // making it easier to prioritize optimization efforts.
  heavyScripts.sort((a, b) => b.totalDuration - a.totalDuration);

  // Log to the console for local debugging. In production, replace
  // this with a call to send the data to your analytics service.
  console.table(heavyScripts);
});

// Use buffered: true to capture any long frames that occurred before
// this observer was registered.
observer.observe({type: 'long-animation-frame', buffered: true});

几个容易被忽略的细节值得展开:

  • 为什么要维护 allScripts:PerformanceObserver 的回调会被多次触发,每次只给出新产生的条目。如果每次都只统计当前批次,某个脚本"单次 20ms、整页调用 30 次"这类累积型问题就会被完全淹没。指南里"heavy-running script 既可能是单个长脚本,也可能是生命周期内多次执行的脚本"这句判断,正是这段累积逻辑的依据。
  • 为什么要按 sourceURL 聚合:同一份 bundle 的不同函数、同一第三方脚本的多次触发,只有按来源汇总 count 与 totalDuration 才能排到同一行,便于把优化工单派给正确的团队。
  • 为什么要阈值过滤:LoAF 数据非常密集,不做过滤会产生大量噪声。示例用的是 totalDuration > 100(毫秒),这是一个起点而非硬编码标准,可按业务对主线程预算的要求调整。
  • 为什么排序:按总耗时降序,保证最该优化的脚本始终排在最前,便于优先级排序。

条目结构与可提取字段

long-animation-frame 条目的 scripts 属性是一个脚本条目数组,每个对象至少包含 sourceURL 与 duration。指南源码中使用的另一个演示文件 demo.html 展示了更细的字段组合:

const observer = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    console.log('Long Animation Frame observed:', entry.duration, 'ms');

    // Iterate through scripts to find the specific function responsible
    // Note script entries will be empty when loading this demo from a
    // local file, instead of from a server.
    for (const script of entry.scripts) {
      console.log(`Script execution time: ${script.duration} ms`);
      console.log(`Function: ${script.sourceFunctionName || '(anonymous)'}`);
      console.log(`URL: ${script.sourceURL}:${script.sourceCharPosition}`);
    }
  }
});

observer.observe({ type: 'long-animation-frame', buffered: true });

这里出现了三个对排障特别有用的字段:sourceURL 定位文件,sourceFunctionName 定位函数(匿名函数时为假值,所以要写 || '(anonymous)' 兜底),sourceCharPosition 定位字符偏移。Demo 里还有一句关键注释:以本地文件方式打开页面时,scripts 数组会是空的,必须通过 HTTP 服务访问才能拿到脚本归因。这一点在做本地验证时极易踩坑。同目录 expectations.md 与 identify-inp-causes 指南 中对脚本条目的命名略有差异(后者写作 PerformanceScriptTiming),写类型声明时建议以目标浏览器的实际 IDL 为准。

正确地"注册观察者":type 与 buffered 的语义

验收标准的第一条其实包含三个隐性约束,它们都能在 grader.ts 里找到对应断言:

  1. 必须使用选项对象形式的 observe({...}),并带有 type 属性;
  2. type 必须是字符串 'long-animation-frame';
  3. buffered 必须为 true;
  4. 不得使用旧式的 entryTypes 数组写法。

type 与 entryTypes 是互斥的两套写法:entryTypes 是早期的批量订阅方式,无法为单个条目类型传入附加选项;type 形式的 API 才允许搭配 buffered。所以"用 type 而不是 entryTypes"并不是风格偏好——一旦退回 entryTypes,就失去 buffered 能力,而 buffered: true 正是验收标准里显式要求的那一项。

buffered: true 的作用是让观察者注册时回放此前已经产生但尚未被消费的条目。这解决了监控脚本的经典时序问题:采集代码通常要等 JS bundle 加载、初始化后才执行,而真正的慢帧很可能发生在首屏渲染或早期初始化阶段。没有 buffered,这段"最贵的时间"会被完全丢弃;加上它,注册之前的帧也能被补回来。这也解释了为什么示例代码把 new PerformanceObserver(...) 放在模块顶层、observe() 紧随其后,而不是等某个组件挂载后再启动。

下面是最小可用骨架,与指南和 Demo 完全一致:

const observer = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    // entry.duration:帧总耗时;entry.scripts:该帧内执行的脚本
  }
});

// 正确:type + buffered
observer.observe({ type: 'long-animation-frame', buffered: true });

// 错误:entryTypes 无法携带 buffered,且被评分器判定为不使用 type 属性
// observer.observe({ entryTypes: ['long-animation-frame'] });

为什么禁止 polyfill

验收标准第二条要求"不为长动画帧引入 polyfill"。这条对应 grader.ts 的静态检查:把被测页面的 HTML 与它通过 <script src> 引用的同目录本地脚本合并成一份代码,然后用正则 /PerformanceLongAnimationFrame\s*=/ 检测是否存在对 PerformanceLongAnimationFrame 的赋值式"伪造实现"。反例文件 negative-demo.html 正是这样写的:

if (!window.PerformanceLongAnimationFrame) {
    window.PerformanceLongAnimationFrame = function() {
        this.duration = 0;
        this.scripts = [];
    };
}

这条禁令有充分的工程理由,而不是"能用原生就别自己写":

  • 打了也没用:LoAF 的数据来自浏览器渲染流水线内部,JS 层无法伪造出真实的 duration 与 scripts。上面这个 polyfill 只会返回 duration = 0 和空脚本列表,等于在监控链路里注入恒定假数据。
  • 会导致错误归因:空结果集会让后续聚合逻辑认为"没有慢脚本",从而掩盖真实问题,比不采集更危险。
  • 规范允许直接使用:指南在「Browser support and fallback strategies」一节明确说明,不支持该 API 的浏览器会忽略这段观察者注册,不会抛错,因此可以安全地无回退使用;而且它识别出的性能问题在多数情况下同样适用于其他浏览器。
  • 仓库对该特性状态使用宏而非硬编码:guide.md 中写的是 {{ BASELINE_STATUS("long-animation-frames") }},由 src/core/macros.ts 在构建时展开为实时的 Baseline 状态;特性本身位于 web-features 数据集,可用 src/cli/baseline-status.ts 通过 pnpm baselinestatus long-animation 查询。相关的样式/布局细分字段 styleDuration 目前仍以 tmp-long-animation-frames-style-layout 形式登记在 features/pending-web-features.json 中,属于尚未定稿的临时特性,这也从侧面说明该生态仍在演进,更不该用自造对象去"补齐"。

评分器如何验证这两条标准

理解评分器的实现,可以帮你自测是否真的达标。grader.ts 采用 Playwright 测试组织,通过环境变量 TARGET_FILE 接收被测页面路径(由 src/grading/run-grader.ts 注入),并以 http://localhost/<文件名>?performance=1&debug=1 打开页面。

第一层:静态断言。合并 HTML 与被引用的本地脚本后,断言代码中不含 PerformanceLongAnimationFrame = 形式的 polyfill。注意 getCombinedCode() 只会收集同目录、经相对路径引用的本地脚本,外链脚本不会被纳入检查范围——这不是漏洞,而是为了让静态检查保持确定性。

第二层:运行时探针。评分器在页面任何脚本执行之前通过 page.addInitScript 注入钩子,把每次 PerformanceObserver.prototype.observe 的入参记录到 window._observeCalls:

const originalObserve = originalPerformanceObserver.prototype.observe;
originalPerformanceObserver.prototype.observe = function(options) {
  (window as any)._observeCalls.push(options);
  try {
    return originalObserve.apply(this, arguments);
  } catch {
    // Swallow errors from the real API to keep the script running for the grader
  }
};

如果环境里没有原生 PerformanceObserver,钩子还会注入一个 mock,其 observe 只记录选项、supportedEntryTypes 里包含 long-animation-frame。这样做的好处是被测代码不会因为环境缺少 API 而崩溃,断言依旧能稳定判定"你写了什么"。

第三层:四条断言。测试随后对 _observeCalls 逐项检查:存在带 type 属性的调用、type 等于 'long-animation-frame'、存在 buffered === true 的调用、且不存在任何带 entryTypes 的调用。最后一条是"负向断言",意味着即使你同时写了 type 和 entryTypes 两种注册方式,也会被判失败——只保留一种正确写法。

本地复现这套校验时,仓库依赖的入口在 package.json 中:pnpm generate-grader 生成评分器,pnpm grade 执行评分,pnpm setup:playwright 安装浏览器。评分器以 src/grading/test-fixture.ts 提供的静态服务器托管被测文件,这也解释了为什么 Demo 必须以服务方式访问才能拿到非空 scripts。

反例逐条拆解

negative-demo.html 是一个刻意写错的版本,它同时违反了上面所有约束,非常适合当作自查对照表:

反例写法 位置 违反的约束 后果
window.PerformanceLongAnimationFrame = function() {...} negative-demo.html 验收标准第二条 注入恒为 0 的假数据,误导归因
obs.observe({ entryTypes: <a href="https://link.gitcode.com/i/a371d3169fcd46dfdfd4960ce9449336" target="_blank">'long-animation-frame'] }) [negative-demo.html 验收标准第一条 无法携带 buffered,丢失注册前的长帧
在回调中用同步 XMLHttpRequest 上报 negative-demo.html 指南最佳实践 监控代码自己阻塞主线程,制造新的长帧
用 setTimeout 计时差反推卡顿 negative-demo.html 指南最佳实践 只能得到"有延迟",拿不到脚本归因

第三条尤其值得强调:指南的示例代码注释里写得很清楚,生产环境应把 console.table 换成向分析服务发送数据;而反例采用的是同步 XHR。采集重脚本的工具本身绝不能变成重脚本,上报应使用 navigator.sendBeacon 这类不阻塞主线程的方式。

从验收标准到生产可用

两条验收标准只保证"入口正确"和"降级克制",要变成可控的线上能力,还需补齐三件事:

  1. 汇总而不是全量上报。指南最佳实践明确要求"对关键信息做摘要",因为 LoAF 条目细节极多,原样上报会显著放大网络与存储成本。按 sourceURL 聚合后的 {sourceURL, count, totalDuration} 就是最小可用的摘要形态。
  2. 做好数据缺失兜底。脚本条目可能为空(例如以 file:// 打开、跨源脚本未暴露信息),sourceFunctionName 也可能缺失,demo.html 中 || '(anonymous)' 就是最小的防御写法。
  3. 与 INP 归因联动。如果你的目标是交互响应性而非纯帧耗时,identify-inp-causes 指南 给出了同源思路:用 web-vitals/attribution 的 onINP() 取 inputDelay、processingDuration、presentationDelay 三个子项,再借助 LoAF 的 longAnimationFrameEntries 判断是脚本、样式重算还是布局拖慢了交互。两份指南共享 long-animation-frames 这一特性 ID,说明帧级归因是 INP 排障的基础设施,而不是替代品。

落地检查清单

在提交实现前,可以逐条对照本指南的契约自查:

  • [ ] 使用 new PerformanceObserver(callback) 注册,回调内遍历 list.getEntries()。
  • [ ] 调用形式为 observe({ type: 'long-animation-frame', buffered: true }),两个选项缺一不可。
  • [ ] 全局搜索确认不存在 entryTypes 形式的注册。
  • [ ] 全局搜索确认不存在 PerformanceLongAnimationFrame = 形式的 polyfill 或自定义实现。
  • [ ] 跨回调累积脚本条目,并按 sourceURL 聚合 count 与 totalDuration。
  • [ ] 设置耗时阈值并降序排序,只上报真正值得优化的脚本。
  • [ ] 生产环境用异步/beacon 方式上报,禁止同步 XHR 或同步存储。
  • [ ] 通过 HTTP 服务而非本地文件验证,确保 scripts 数组非空。

这八条中,前四条来自 expectations.md 与 grader.ts 的硬性校验,后四条来自 guide.md 的最佳实践与 demo.html 的工程细节。把验收标准和实现细节对齐之后,你得到的不是一个能跑通的 demo,而是一条可以在真实用户环境长期运行、且不会自我伤害的性能观测链路。

登录后查看全文
modern-web-guidance-src