使用window.performance对应用性能监测

window.performance是HTML5 的一个新API。

API详细文档传送门:https://developer.mozilla.org/en-US/docs/Web/API/Window/performance


浏览器一般的加载顺序如下图:

 

所以根据上面的时间点,我们可以计算常规的性能值,如下:

(使用该api时需要在页面完全加载完成之后才能使用,最简单的办法是在window.onload事件中读取各种数据,因为很多值必须在页面完全加载之后才能得出。)

 

var timing = window.performance && window.performance.timing;

var navigation = window.performance && window.performance.navigation;

 

 

重定向次数:

var redirectCount = navigation && navigation.redirectCount;

 

跳转耗时:

var redirect = timing.redirectEnd - timing.redirectStart;

 

APP CACHE 耗时:
var appcache = Math.max(timing.domainLookupStart - timing.fetchStart, 0);

 

DNS 解析耗时:
var dns = timing.domainLookupEnd - timing.domainLookupStart;

 

TCP 链接耗时:
var conn = timing.connectEnd - timing.connectStart;

 

等待服务器响应耗时(注意是否存在cache):
var request = timing.responseStart - timing.requestStart;

 

内容加载耗时(注意是否存在cache):
var response = timing.responseEnd - timing.responseStart;

 

总体网络交互耗时,即开始跳转到服务器资源下载完成:
var network = timing.responseEnd - timing.navigationStart;

 

渲染处理:
var processing = (timing.domComplete || timing.domLoading) - timing.domLoading;

 

抛出 load 事件:
var load = timing.loadEventEnd - timing.loadEventStart;

 

总耗时:
var total = (timing.loadEventEnd || timing.loadEventStart || timing.domComplete || timing.domLoading) - timing.navigationStart;

 

可交互:
var active = timing.domInteractive - timing.navigationStart;

 

请求响应耗时,即 T0,注意cache:
var t0 = timing.responseStart - timing.navigationStart;

 

首次出现内容,即 T1:
var t1 = timing.domLoading - timing.navigationStart;

 

内容加载完毕,即 T3:
var t3 = timing.loadEventEnd - timing.navigationStart;

posted @ 2015-04-01 16:37  Joy Ho  阅读(1178)  评论(1编辑  收藏  举报