首页 > 解决方案 > 如何使用性能观察者 api 查找长任务信息

问题描述

我正在学习性能观察者 API,我想知道代码中有多少长任务,所以我写了这段代码:

const observer = new PerformanceObserver((list) => { 
  for (const entry of list.getEntries()) { 
    console.log(entry); 
  }
}); 
observer.observe({entryTypes: ['longtask']});

现在我得到的就是这个

在此处输入图像描述

谁能告诉我如何找出哪个任务是长任务我的意思是什么导致它或它发生在哪里?

标签: javascriptperformanceapi

解决方案


除非您正在查看默认标记,例如在 Chrome DevTools 的“性能”选项卡中可见的首次绘制、脚本、XMLHttpRequest...等,否则我相信您需要设置命名标记以利用用户计时 API .

performance.mark("start_test") // start the timer

await doWork(); // the function you want to test

performance.mark("end_test") // start the timer    

performance.getEntriesByName("test").forEach(entry => {
        // Display each reported measurement on console
        if (console) {
            console.log("Name: "       + entry.name      +
                      ", Type: "     + entry.entryType +
                      ", Start: "    + entry.startTime +
                      ", Duration: " + entry.duration  + "\n");
        }
      })

推荐阅读