不用充钱买性能工具了?浏览器这套免费API我劝你先用起来

前端性能分析动不动就要充钱买工具,其实浏览器早就给你准备好了全套API,只是多数人只用了console.time凑合。今天把Performance API拆开讲,从获取指标到自定义测量,手把手教你用它替代大部分付费工具。


浏览器自带一套完整的性能数据接口,统称Performance API。打开Chrome控制台,随便找个页面输入performance,回车就能看到一堆数据——navigation、timing、memory、eventCounts……这些东西你每天都在用,但可能从来没仔细看过。

先说最基础的performance.timing这张时间表。页面从输入URL到渲染完成,中间经历DNS解析、TCP连接、TLS握手、DOM解析、CSS计算、布局、绘制——每一个步骤耗时都被记录下来了。你不需要装任何SDK,直接在控制台敲几行代码就能看到:

const { navigationStart, domContentLoaded, loadEventEnd } = performance.timing;
console.log(`DOMContentLoaded: ${domContentLoaded - navigationStart}ms`);
console.log(`PageLoad: ${loadEventEnd - navigationStart}ms`);

但这张表只是骨架,真正的精髓在PerformanceObserver。这东西能实时监听性能指标变化,不像传统方式要等你手动去查。

const observer = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    console.log(`${entry.name}: ${entry.startTime.toFixed(2)}ms`);
  }
});

observer.observe({ type: 'paint', buffered: true });
observer.observe({ type: 'largest-contentful-paint', buffered: true });
observer.observe({ type: 'layout-shift', buffered: true });

这段代码监听了绘制事件、LCP和CLS。buffered:true的意思是把我注册之前已经发生的也读出来,不用等下次发生。跑一下,控制台立刻打印出白屏时间、首次内容绘制时间——这些指标以前要么靠插件,要么靠PageSpeed Insights查,现在浏览器直接给你。

再说一个实际场景:你想知道某个异步操作耗时多少,不用再自己写Date.now()算差值。performance.mark和performance.measure是专门干这个的:

performance.mark('fetch-start');
fetch('/api/data').then(() => {
  performance.mark('fetch-end');
  performance.measure('API耗时', 'fetch-start', 'fetch-end');

  const measure = performance.getEntriesByName('API耗时')[0];
  console.log(`接口耗时: ${measure.duration.toFixed(2)}ms`);

  performance.clearMarks();
  performance.clearMeasures();
});

measure会自动算出两个mark之间的时长,还能起个好记的名字。你可以在多个关键节点埋点,把整个用户旅程的耗时曲线画出来。

Resource Timing是另一个利器,专门追踪静态资源和接口请求:

const resourceObserver = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    if (entry.initiatorType === 'fetch' || entry.initiatorType === 'xmlhttprequest') {
      console.log(`接口: ${entry.name}`);
      console.log(`  DNS: ${entry.domainLookupEnd - entry.domainLookupStart}ms`);
      console.log(`  TCP: ${entry.connectEnd - entry.connectStart}ms`);
      console.log(`  TTFB: ${entry.responseStart - entry.requestStart}ms`);
      console.log(`  下载: ${entry.responseEnd - entry.responseStart}ms`);
    }
  });
});
resourceObserver.observe({ type: 'resource', buffered: true });

每个资源的DNS解析用了多久、TCP握手多久、服务器响应多久、下载多久,一行行全部分解。哪个接口拖后腿、哪个静态资源太大,一目了然。

现在主流的性能方案是采集真实用户数据上报到服务端,生成自己的性能大盘。Performance API配合navigator.sendBeacon可以实现无阻塞上报:

const reportPerformance = () => {
  const entries = performance.getEntriesByType('navigation')[0];
  const data = {
    page: location.pathname,
    ttfb: entries.responseStart - entries.requestStart,
    fcp: performance.getEntriesByName('first-contentful-paint')[0]?.startTime,
    lcp: performance.getEntriesByName('paint')[0]?.startTime,
    cls: 0, // 需单独计算
    timestamp: Date.now(),
    userAgent: navigator.userAgent,
  };
  navigator.sendBeacon('/analytics', JSON.stringify(data));
};
window.addEventListener('load', reportPerformance);

sendBeacon保证页面卸载时数据也能发出去,不会因为页面关闭就丢请求。结合自己的数据看板,你可以做到分钟级告警,而不是等用户反馈才知道慢了。

最后列几个我常用的调试命令,平时排查性能问题够用了:

// 查看当前页面所有性能指标
console.table(performance.getEntriesByType('paint'));

// 查看内存占用(需Chrome开启亚毫秒精度)
console.log(performance.memory);

// 查看帧率
const fpsObserver = new PerformanceObserver((list) => {
  list.getEntries().forEach(e => console.log('FPS:', Math.round(e.sources[0].duration ? 1000/e.sources[0].duration : 0));
});
fpsObserver.observe({ type: 'frame', buffered: true });

Performance API不是什么新东西,Chrome从很早就支持了。关键是你愿不愿意把这些零散接口串起来用,形成自己团队的性能监测体系。现在就开始用,控制台就是你的第一个性能面板——免费、无依赖、不充钱。

评论区

0 条评论

登录后可评论。

阿速·性能优化 261 阅读