Performance API 是浏览器提供给咱们的用于检测网页性能的 API,它并非一个孤立的 API,而是一组 API 的组合。主要包括:javascript
上面三个接口,又都继承自 Performance Timeline API 中的 PerformanceEntry 接口,因此每一个接口实例叫作 Entry。PerformanceEntry 中定义了四个基本的只读属性:name、entryType、startTime 和 duration。html
为了方便理解,如今打开地址:www.w3.org/TR/performa…,调出控制台,复制下面的代码(来自 MDN)执行,就能看到网页从导航到显示中间的耗时统计信息。java
// See: https://developer.mozilla.org/en-US/docs/Web/API/PerformanceEntry#Example
function print_PerformanceEntries() {
// Use getEntries() to get a list of all performance entries
var p = performance.getEntries();
for (var i=0; i < p.length; i++) {
console.log("PerformanceEntry[" + i + "]");
print_PerformanceEntry(p[i]);
}
}
function print_PerformanceEntry(perfEntry) {
var properties = ["name",
"entryType",
"startTime",
"duration"];
for (var i=0; i < properties.length; i++) {
// Check each property
var supported = properties[i] in perfEntry;
if (supported) {
var value = perfEntry[properties[i]];
console.log("... " + properties[i] + " = " + value);
} else {
console.log("... " + properties[i] + " is NOT supported");
}
}
}
// 打印网页
print_PerformanceEntries()
复制代码
window 对象上暴露了一个 performance 属性,这个属性提供了 getEntries 方法,能够用来获取整个页面的性能实体列表(performance entries),这些实体对象中包含了从不一样角度记录的耗时信息;接下来再对获得的结果使用 for 循环遍历出来。git
下面是在我控制台上的打印结果:github
本文只介绍导航阶段(也都是上面打印的第一条数据)的统计信息。其余两个按照下面一样的思路分析便可。面试
进入页面,首先统计的就是页面从导航一直到 load 事件结束的过程,这些信息都保存在了 PerformanceNavigationTiming 实例中。字段解释以下:api
更加完整的信息能够经过使用 performance.getEntries()[0] 得到: 浏览器
图片取自 www.w3.org/TR/navigati…缓存
是否是有种似曾相识的感受呢?最近有面试或者曾经有面试的同窗,确定有被问过“从输入 URL 到页面展现,这中间发生了什么?”的问题,而上面的流程正好对应整个过程。cookie
如今,咱们就上面的流程,来一个个解析 PerformanceNavigationTiming 实例中所涉及到的各个属性的含义。
startTime: 开始导航的时间。加载新页面、当前页面卸载时会触发 unload 事件。若是当前页面有未提交的表单数据等状况,会弹出一个确认关闭框。点击确认后,导航流程开始。startTime 值几乎总为 0。
unloaStart、unloadEnd:对应页面 unload 事件,标记该事件的开始和结束时间。
redirectStart、redirectEnd:若是页面发生了重定向,redirectStart 表示重定向开始时间,redirectEnd 表示重定向结束时间。若是没有重定向,redirectStart、redirectEnd 值都为 0。
fetchStart:下一步,取浏览器本地缓存(强缓存,若是本地缓存过时,还有一个走协商缓存的过程)。fetchStart 表示开始取缓存时间。
domainLookupStart、domainLookupEnd:从域名到 IP 地址有一个 DNS 解析过程。domainLookupStart、domainLookupStart 分别标记解析开始和结束时间。
connnectStart、connectEnd、secureConnectEnd:获得 IP 地址,正式开始请求以前,进行 TCP 链接。connnectStart 记录链接的开始时间,若是使用的 https 协议,还有一个创建 STL 链接,获得会话密钥的过程,使用 secureConnectStart 字段记录。
requestStart:接下来发起真正的 HTTP 请求,构建请求头信息,携带 cookie 字段信息等。
responseStart、responseEnd:响应开始和结束时间(先接收响应头,再接收响应体)。
domInteractive、domContentLoadedEventStart、domContentLoadedEventEnd、domComplete:domInteractive、domComplete 能够对应到 document readystatechange 事件 上的 interactive、complete 值(document.readyState 属性的两个可用取值)。domContentLoadedEventStart、domContentLoadedEventEnd 则对应 document DOMContentLoaded 事件,标记事件的开始和结束时间。
loadStart、loadEnd:这里对应的是 load 事件(当页面资源(脚本、样式、图片、音视频、iframe 等)所有加载完成后),标记事件的开始和结束时间。
至此,梳理完成 PerformanceNavigationTiming 实例全部核心属性的含义。
Cloudflare 公司 在自家的统计系统中,就使用了 PerformanceNavigationTiming 实例信息,对网页性能作了统计。展现效果以下:
(完)