perf-reporter.js
2.7 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
var cookies = require('../cookie');
var reporter = require('./reporter');
var perfKey = '_perfLog';
var resourcePerf = require('./perf/resource'),
timingPerf = require('./perf/timing');
var perfReporter = {
init: function(debug) {
this.debug = debug;
this.dataList = [];
resourcePerf.init(this.debug);
timingPerf.init(this.debug);
this.report();
var self = this;
window.addEventListener && window.addEventListener('load', function() {
setTimeout(function() {
self.collect();
}, 0);
});
},
collect: function() {
try {
var timingPerfData = timingPerf.collect();
var resourcePerfData = resourcePerf.collect();
this.chunk(timingPerfData);
for (var i = 0; i < resourcePerfData.length; i++) {
this.chunk(resourcePerfData[i]);
}
} catch(e) {
if (this.debug) {
console.log(e);
}
}
},
getMeta: function() {
return {
pt: encodeURIComponent(window.location.href), // url
ua: encodeURIComponent(navigator.userAgent), // useragent
u: reporter.getUid(), // uid
ud: reporter.getUdid(), // udid
rid: reporter.getReqId(), // reqId
r: reporter.getRoute() // server route
}
},
jsonConcat: function(object1, object2) {
for (var key in object2) {
object1[key] = object2[key];
}
return object1;
},
write: function(item) {
var perfList = JSON.parse(cookies(perfKey) || '[]');
this.jsonConcat(item, this.getMeta());
perfList.push(item);
cookies(perfKey, JSON.stringify(perfList));
if (perfList.length >= 5) {
this.report();
}
},
report: function() {
var self = this;
var perfList = JSON.parse(cookies(perfKey) || '[]');
var perfStr = reporter.stringify(perfList);
reporter.report(perfStr, function() {
self.clear();
});
},
clear: function() {
cookies(perfKey, '[]');
},
chunk: function(item) {
var self = this;
this.dataList.push(item);
function _write() {
if (self.dataList.length === 0) {
return
}
var data = self.dataList.shift();
self.write(data);
setTimeout(_write, 10)
}
setTimeout(function() {
_write();
}, 10)
}
};
if (window._perfEnable_) {
perfReporter.init(true);
}