timing.js
3.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
var timingReporter = function() {
var _dnsTime = performance.timing.domainLookupEnd - (performance.timing.domainLookupStart || 0),
_tcpTime = performance.timing.connectEnd - (performance.timing.connectStart || 0),
_responseTime = performance.timing.responseEnd - (performance.timing.responseStart || 0),
_emptyScreenTime = performance.timing.responseStart - (performance.timing.navigationStart || 0),
_parseDomTime = performance.timing.domContentLoadedEventEnd - (performance.timing.domLoading || 0),
_domReadyTime = performance.timing.domContentLoadedEventEnd - (performance.timing.navigationStart || 0),
_roundtripTime = (performance.timing.loadEventEnd || performance.timing.domComplete) - (performance.timing.navigationStart || 0);
function getResults() {
return {
tp: 'timing',
dtp: 'html',
dt: Math.floor(_dnsTime), // DNS 时间
tt: Math.floor(_tcpTime), // TCP 建立时间
rt: Math.floor(_responseTime), // request 建立时间 // 下载时间
domt: Math.floor(_parseDomTime), // 解析 dom 树时间
et: Math.floor(_emptyScreenTime), // 白屏时间,用户可见, start render
ot: Math.floor(_domReadyTime), // 用户可交互时间, start interact
rtt: Math.floor(_roundtripTime), // 总时间, start page load
wd: screen.width || 1, // 屏幕宽
hg: screen.height || 1, // 屏幕高
pf: navigator.platform || 'unknown' // 系统
};
}
return {
collect: function() {
return getResults();
},
print: function() {
var debug = document.getElementById("debug");
var output = this.formatDebugInfo();
if (!debug) {
var divTag = document.createElement("div");
divTag.id = "debug";
divTag.innerHTML = output;
document.body.appendChild(divTag);
} else {
debug.innerHTML += output;
}
},
formatDebugInfo: function() {
var debuginfo = "<p>";
debuginfo += "timing object : " + JSON.stringify(this.collect(), null, 2) + "<br/>";
debuginfo += "url: " + decodeURIComponent(window.location.href) + "<br/>";
debuginfo += "</p>";
return debuginfo
}
}
};
var reporter = {
init: function(debug) {
this.enable = true;
this.debug = debug;
if (!('performance' in window)) {
this.enable = false;
return;
}
},
collect: function() {
if (!this.enable) {
return;
}
var perf = timingReporter();
var data = perf.collect();
if (this.debug) {
perf.print();
}
return data;
}
};
module.exports = reporter;