1. developer tool performance
我们可以通过performance来看到我们页面的一些性能指标:FP、FCP、FMP...(详情)
2. js 调用performanceOberver来获取性能指标数据
一般在html的<head>中添加这样的代码:
<script> const observer = new PerformanceObserver((list) => { for (const entry of list.getEntries()) { console.groupCollapsed(entry.name) console.log(entry.entryType); console.log(entry.startTime); // DOMHighResTimeStamp console.log(entry.duration); // DOMHighResTimeStamp console.groupEnd(entry.name) } }); observer.observe({ entryTypes: [‘longtask‘, ‘frame‘, ‘navigation‘, ‘resource‘, ‘mark‘, ‘measure‘, ‘paint‘] }); </script>
entryTypes文档记载有6种:frame
,navigation,
resource,mark,measure,paint(详情),但是查看实际demo的时候却发现还有longtask
大概效果:
3. 结合google anlyasis工具帮助我们分析性能
通过ga(google-analytics)工具,发送性能数据给google-analytics平台,让平台记录并且生成一些性能报表
这些代码可以放到我们的线上环境,通过大量用户的访问,来获取大量的性能数据。(详情)
不过,我们需要先注册一个账号,申请一个“跟踪ID”(官网)
<script> window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date; ga(‘create‘, ‘UA-XXXXX-Y‘, ‘auto‘); ga(‘send‘, ‘pageview‘); </script> <script async src=‘https://www.google-analytics.com/analytics.js‘></script> <!-- Register the PerformanceObserver to track paint timing. --> <script> const observer = new PerformanceObserver((list) => { for (const entry of list.getEntries()) { // `name` will be either ‘first-paint‘ or ‘first-contentful-paint‘. const metricName = entry.name; const time = Math.round(entry.startTime + entry.duration); ga(‘send‘, ‘event‘, { eventCategory:‘Performance Metrics‘, eventAction: metricName, eventValue: time, nonInteraction: true, }); } }); observer.observe({entryTypes: [‘paint‘]}); </script>
原文:https://www.cnblogs.com/amiezhang/p/10816673.html