互联网产品开发过程中,想了解用户体验一直是一件比较困难的事情。之前很难使用js获得用户访问网站的连接建立时间、dns时间等信息,想得到这些信息一般是建立固定的监测点或者使用专门的测试客户端软件。不过,现在情况有所改变,IE9和chrome6以上的版本都支持了一个新的api:window.performance( ie9中为window.msPerformance,chrome6-9为window.webkitPerformance,chrome10中是window.performance)(2012/6/19注:今天在本博客的测速日志里发现了firefox13和360浏览器,这说明现在这个api至少又多了两个浏览器支持)。该api目前在W3C上的状态是“Candidate Recommendation”,相信会有越来越多的浏览器支持。废话不多说,我们来看一下这个api能干哪些事情。

首先,该api的的接口定义为:


interface PerformanceTiming {
 readonly attribute unsigned long long navigationStart;
 readonly attribute unsigned long long unloadEventStart;
 readonly attribute unsigned long long unloadEventEnd;
 readonly attribute unsigned long long redirectStart;
 readonly attribute unsigned long long redirectEnd;
 readonly attribute unsigned long long fetchStart;
 readonly attribute unsigned long long domainLookupStart;
 readonly attribute unsigned long long domainLookupEnd;
 readonly attribute unsigned long long connectStart;
 readonly attribute unsigned long long connectEnd;
 readonly attribute unsigned long long secureConnectionStart;
 readonly attribute unsigned long long requestStart;
 readonly attribute unsigned long long responseStart;
 readonly attribute unsigned long long responseEnd;
 readonly attribute unsigned long long domLoading;
 readonly attribute unsigned long long domInteractive;
 readonly attribute unsigned long long domContentLoadedEventStart;
 readonly attribute unsigned long long domContentLoadedEventEnd;
 readonly attribute unsigned long long domComplete;
 readonly attribute unsigned long long loadEventStart;
 readonly attribute unsigned long long loadEventEnd;
};

这些变量都表示神马意思呢?莫急,看看浏览器的一般加载顺序,下图所示:
浏览器页面加载顺序图从上图就可以看出这些变量的具体含义了,这时想得到用户浏览器加载过程的各项指标就简单了。比如想拿到用户的dns时间,只需要拿domainLookupEnd减去domainLookupStart即可。

不过,在chrome下,这里有一个坑,按照W3C的标准,navigationStart应该是整个过程的开始,也就是时间点应该最早。但是chrome下很多时候不是这样,会有domainLookupStart时间早于navigationStart的情况,初步认为应该是chrome的各种优化机制和预渲染功能打乱了上图的顺序。IE9相对守规矩一点。

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