resource.js
2.71 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
83
84
85
86
87
88
89
90
91
var resourceReporter = {
init: function(debug) {
this.enable = true;
this.debug = debug;
if (!('performance' in window) ||
!('getEntriesByType' in window.performance) ||
!(window.performance.getEntriesByType('resource') instanceof Array)
) {
this.enable = false;
return;
}
this.whiteList = [/^https:\/\/img\d*.static.yhbimg.com/, /^https:\/\/cdn.yoho.cn/];
},
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>resource object: <br/>";
var data = this.getData();
for (var i = 0; i < data.length; i++) {
debuginfo += JSON.stringify(data[i], null, 2) + "<br/>";
}
debuginfo += "</p>";
return debuginfo
},
filter: function(url) {
for (var i = 0; i < this.whiteList.length; i++) {
if (this.whiteList[i].test(url)) {
return true;
}
}
return false;
},
getData: function() {
var resources = window.performance.getEntriesByType('resource');
var resourceList = [];
for (var obj in resources) {
var domObj = resources[obj];
if (!this.filter(domObj.name)) {
continue;
}
resourceList.push({
tp: 'resource', // 资源
dtp: domObj.entryType, // 资源
id: domObj.name || 'unknown', // 资源 url
rtp: domObj.initiatorType || 'unknown', // 资源类型 img script
dt: Math.floor(domObj.domainLookupEnd - domObj.domainLookupStart || 0), // DNS 时间
tt: Math.floor(domObj.connectEnd - domObj.connectStart || 0), // tcp 时间
rt: Math.floor(domObj.responseEnd - domObj.responseStart || 0), // 下载 时间
rrt: Math.floor(domObj.responseEnd - domObj.fetchStart || 0) // 总时间
})
}
return resourceList;
},
collect: function() {
if (!this.enable) {
return;
}
if (this.debug) {
this.print();
}
return this.getData();
}
};
module.exports = resourceReporter;