-
Notifications
You must be signed in to change notification settings - Fork 7
/
uxfirst.js
87 lines (69 loc) · 2.2 KB
/
uxfirst.js
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
(function(global){
'use strict';
var doc = global.document;
var storage = global.localStorage;
var perf = global.performance;
if (!doc.addEventListener) {
return;
}
// Only keep the metrics for the last 2 hours
var timeout = 7200000;
var startTime = Date.now();
// Wait for the document ready event
function checkIfDocumentIsComplete() {
if (doc.readyState === 'complete') {
setTimeout(saveLoadTime, 2);
return true;
}
return false;
}
if (!checkIfDocumentIsComplete()) {
doc.addEventListener('readystatechange', checkIfDocumentIsComplete);
}
// Get the load time from the Timing API (if available)
function saveLoadTime() {
var currentPageLoadTime;
var newData = [];
if (perf && perf.timing) {
currentPageLoadTime = perf.timing.loadEventEnd - perf.timing.fetchStart;
} else {
// For browsers that don't support Navigation API
currentPageLoadTime = Date.now() - startTime;
}
// Get the previous pages timings
var localData = readLocalStorage();
// Remove the timings too old
for (var i=0, max=localData.length ; i<max ; i++) {
if (localData[i].d + timeout > startTime) {
newData.push(localData[i]);
}
}
// Add the new timing
newData.push({
d: startTime,
l: currentPageLoadTime
});
// Save
storage.setItem('uxfirst', JSON.stringify(newData));
}
function readLocalStorage() {
var localData = storage.getItem('uxfirst');
if (!localData) {
return [];
}
return JSON.parse(localData);
}
global.uxFirst = function(minNumberOfMeasures) {
var minNumber = minNumberOfMeasures || 1;
var localData = readLocalStorage();
var dataLength = localData.length;
var sum = 0;
if(dataLength < minNumberOfMeasures) {
return null;
}
for (var i=0, max=dataLength ; i<max ; i++) {
sum += localData[i].l;
}
return sum / dataLength;
};
}(this));