在 TypeScript 前端程序中测量 Web 性能指标

Measuring web performance metrices in TypeScript front end program

我的前端是用 Angular9, TypeScript 写的。

我有兴趣按照 W3 工作组 W3 performance working group.

的建议,用不同的页面加载时间性能指标(浏览器计时和 DOM 处理)来注释我的应用程序

如何开始在我的 TypeScript 应用程序中导入 Performance 对象,以便我可以开始监控提到的不同性能指标 here

谢谢, 普拉迪普

性能 API 由浏览器提供,因此如果您希望直接使用它们,则无需导入任何内容。我已经在 MDN:

上复制了示例
function print_nav_timing_data() {
  // Use getEntriesByType() to just get the "navigation" events
  var perfEntries = performance.getEntriesByType("navigation");

  for (var i=0; i < perfEntries.length; i++) {
    console.log("= Navigation entry[" + i + "]");
    var p = perfEntries[i];
    // dom Properties
    console.log("DOM content loaded = " + (p.domContentLoadedEventEnd - p.domContentLoadedEventStart));
    console.log("DOM complete = " + p.domComplete);
    console.log("DOM interactive = " + p.domInteractive);
 
    // document load and unload time
    console.log("document load = " + (p.loadEventEnd - p.loadEventStart));
    console.log("document unload = " + (p.unloadEventEnd - p.unloadEventStart));
    
    // other properties
    console.log("type = " + p.type);
    console.log("redirectCount = " + p.redirectCount);
  }
}

但是,如果您只对衡量这些特定指标感兴趣,则可以使用他们提供的 web-vitals 项目 here。用法如下所示:

import {getFCP} from 'web-vitals';

// Measure and log the current FCP value,
// any time it's ready to be reported.
getFCP(console.log);

由于源代码可用,您也可以看到他们如何使用 API。