-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
100 lines (81 loc) · 2.33 KB
/
index.js
File metadata and controls
100 lines (81 loc) · 2.33 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
/**
* painty - A First Meaningful Paint metric collector based on MutationObserver with a setTimeout
* fallback
* @author jasonslyvia
*/
var timing = require('timing2');
var calculateFMP = require('./calculateFMP');
/* global __PAINTY_STACK_LIMIT__ */
// record at most 100 DOM changes
var STACK_LIMIT = typeof __PAINTY_STACK_LIMIT__ === 'number' ? __PAINTY_STACK_LIMIT__ : 100;
function now() {
return typeof performance === 'object' && typeof performance.now === 'function' ? performance.now() : Date.now();
}
module.exports = function painty(timeout, callback) {
if (typeof window !== 'object' || typeof timing !== 'object') {
return;
}
if (typeof timeout === 'function') {
callback = timeout;
}
var records = [];
function logDOMChange() {
if (typeof MutationObserver === 'function') {
var observer = new MutationObserver(function() {
records.push({
t: now(),
domCnt: document.getElementsByTagName('*').length,
});
if (records.length === STACK_LIMIT) {
done();
}
});
observer.observe(document, {
childList: true,
subtree: true,
});
return observer.disconnect.bind(observer);
}
var timer = setTimeout(function() {
records.push({
t: now(),
domCnt: document.getElementsByTagName('*').length,
});
if (records.length === STACK_LIMIT) {
done();
} else {
logDOMChange();
}
}, 200);
return function() {
clearTimeout(timer);
};
}
var stopLogging = logDOMChange();
function done() {
stopLogging();
if (typeof timing !== 'object' || typeof timing.getEntriesByType !== 'function') {
return;
}
var navTimings = timing.getEntriesByType('navigation');
if (!navTimings || !navTimings.length) {
return;
}
var navTiming = navTimings[0];
var start = navTiming.startTime;
callback(calculateFMP({
records: records,
start: start,
timeout: timeout,
load: navTiming.duration,
}));
}
if (typeof timeout === 'number') {
setTimeout(done, timeout);
} else {
var ua = navigator.userAgent;
var isMobileSafari = !!ua.match(/iPhone|iPad|iPod/i);
var eventName = isMobileSafari ? 'pagehide' : 'beforeunload';
window.addEventListener(eventName, done);
}
};