前端性能指标计算方法

performace的兼容写法  

var t = new Object();
var performance =
      window.performance || window.msPerformance || window.webkitPerformance;
var resource =  performance.getEntriesByType('resource') 
 if (
        resource &&
       resource[0]
      ) {
        t = resource[0];
      } else if (performance && performance.timing) {
        t = performance.timing;
      }

1、DNS查询耗时

t.domainLookupEnd - t.domainLookupStart || 0;

PerformaceTiming.domainLookupStart为域名开始解析时的 Unix毫秒时间戳

PerformaceTiming.domainLookupEnd为解析域名结束时的 Unix毫秒时间戳,

2、TCP建立连接耗时

t.connectEnd - t.connectStart;

PerformaceTiming.connectStart HTTP请求开始向服务器发送时的Unix毫秒时间戳

PerformaceTiming.connected浏览器与服务器之间的连接建立时的Unix毫秒时间戳

3、TTFB收到第一字节耗时

t.responseStart - t.requestStart;

PerformaceTiming.responseStart浏览器从服务器收到(或从本地缓存读取)第一个字节时的Unix毫秒时间戳

PerformaceTiming.requestStart浏览器向服务器发出HTTP请求时(或开始读取本地缓存时)的Unix毫秒时间戳。

4、Trans文本传输耗时

t.responseEnd - t.responseStart

PerformaceTiming.responseEnd浏览器从服务器收到(或从本地缓存读取,或从本地资源读取)最后一个字节时(如果在此之前HTTP连接已经关闭,则返回关闭时)的Unix毫秒时间戳。

5、Dom DOM结构解析耗时

body完成,header中写的js(不含defer属性)会影响该值.

t.domInteractive - t.responseEnd;

PerformaceTiming.domInteractive当前网页DOM结构结束解析、开始加载内嵌资源时(即Document.readyState属性变为“interactive”、相应的readystatechange事件触发时)的Unix毫秒时间戳。

PerformaceTiming.responseEnd浏览器从服务器收到(或从本地缓存读取,或从本地资源读取)最后一个字节时(如果在此之前HTTP连接已经关闭,则返回关闭时)的Unix毫秒时间戳。  

6、SSL安全链接耗时

t.connectEnd - t.secureConnectionStart;

PerformaceTiming.connected浏览器与服务器之间的连接建立时的Unix毫秒时间戳

PerformaceTiming.secureConnectionStart浏览器与服务器开始安全链接的握手时的Unix毫秒时间戳

7、FP首次绘制

 if (performance && performance.getEntries) {
          var perfEntries = performance.getEntries();
          for (var key in perfEntries) {
            if (
              perfEntries[key].name &&
              perfEntries[key].name === 'first-contentful-paint' &&
              perfEntries[key].startTime
            ) {
              var fcp = perfEntries[key].startTime.toFixed(0) * 1;
            }
            if (
              perfEntries[key].name &&
              perfEntries[key].name === 'first-paint' &&
              perfEntries[key].startTime
            ) {
             var  fp = perfEntries[key].startTime.toFixed(0) * 1;
            }
          }
        }

  

8、FCP首次内容绘制

 perfEntries[key].startTime.toFixed(0) * 1;  

9、重定向耗时  

 if (t.navigationStart !== undefined) {
     rd = t.fetchStart - t.navigationStart
 } else if (t.redirectEnd !== undefined) {
     rd = t.redirectEnd - t.redirectStart
 } else {
     rd = 0
 }

10、FMP有意义的绘画时间

https://github.com/iyjhabc/first-meaningful-paint/blob/master/src/index.js 

11、TTI html加载耗时

t.domInteractive - t.fetchStart;

PerformaceTiming.fetchStart,表征了浏览器准备好使用HTTP请求来获取(fetch)文档的UNIX时间戳。这个时间点会在检查任何应用缓存之前。

12、Ready  domContentLoaded耗时

t.domContentLoadedEventEnd - t.fetchStart

13、onload 加载完成耗时

t.loadEventStart - t.fetchStart;

  

  

参考: https://developer.mozilla.org/zh-CN/docs/Web/API/PerformanceTiming

posted @ 2019-12-19 12:00  地铁程序员  阅读(1302)  评论(0编辑  收藏  举报