企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] ## 概述 监听页面中耗时过长的操作,或者资源加载时间等 ## demo ``` <body> <div> <button onclick="runMeasure()">measure</button> <button onclick="runLongtask()">longtask</button> <button onclick="runNotLongtask()">not longtask</button> </div> <div id="output"> </div> <script> let $output = document.querySelector('#output'); if(!('PerformanceObserver' in window)) { $output.innerHTML = '您的浏览器不支持 PerformanceObserver API'; } const observer = new PerformanceObserver((list) => { let output; for (const item of list.getEntries()) { console.log(item); output = { entryType: item.entryType, name: item.name, startTime: item.startTime, duration: item.duration }; $output.innerHTML += '<pre>' + JSON.stringify(output) + '</pre>'; if(item.entryType === 'longtask') { report(); } } }); // resource 资源加载时间 如 js,css observer.observe({ entryTypes: ['mark', 'measure', 'longtask', 'paint', 'navigation', 'resource',] }); //events function runMeasure () { //performance.mark 可触发 mark 事件 performance.mark('start') var now = new Date(); while (new Date() - now < 40) { } performance.mark('end') console.error(performance.now()); // performance.measure 可触发 measure 事件 performance.measure('taskA_mark', 'start', 'end'); } //模拟长任务 function runLongtask () { var now = new Date(); while (new Date() - now < 1 * 1000) { } } //短任务 function runNotLongtask() { var now = new Date(); while (new Date() - now < 30) { } } //上报 function report (funName) { fetch('/report/to/path?longtask=1') } </script> </body> ``` ![](https://img.kancloud.cn/55/bc/55bc1271af352e1eadfbd46786b7afd6_1095x274.png)