頁面性能監測

1. developer tool performance
咱們能夠經過performance來看到咱們頁面的一些性能指標:FP、FCP、FMP...(詳情
html

 


2. js 調用performanceOberver來獲取性能指標數據
通常在html的<head>中添加這樣的代碼:web

<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種:framenavigation,resource,mark,measure,paint詳情),可是查看實際demo的時候卻發現還有longtask
大概效果:async

 

3. 結合google anlyasis工具幫助咱們分析性能工具

經過ga(google-analytics)工具,發送性能數據給google-analytics平臺,讓平臺記錄而且生成一些性能報表性能

這些代碼能夠放到咱們的線上環境,經過大量用戶的訪問,來獲取大量的性能數據。(詳情google

不過,咱們須要先註冊一個帳號,申請一個「跟蹤ID」(官網spa

<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>
相關文章
相關標籤/搜索