forked from carbon-app/carbon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hooks.js
65 lines (60 loc) · 1.82 KB
/
hooks.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
import React from 'react'
function userTiming({ category, status, value }) {
try {
window.gtag('event', status, {
event_category: 'Performance',
event_label: category,
value,
})
} catch (err) {
// pass
}
}
export function usePerformanceMeasurement() {
React.useEffect(() => {
try {
if (window.performance && window.performance.getEntriesByType) {
window.performance.getEntriesByType('paint').forEach(entry => {
userTiming({
category: 'paint',
status: entry.name,
value: entry.startTime,
})
})
const navigationTiming = window.performance.getEntriesByType('navigation')
? window.performance.getEntriesByType('navigation')[0]
: null
if (navigationTiming) {
userTiming({
category: 'paint',
status: 'time to first byte',
value: navigationTiming.responseEnd - navigationTiming.requestStart,
})
}
const javascriptFiles = performance.getEntries().filter(resource => {
return resource.name.startsWith(`${location.origin}/_next/static`)
})
/*
* Tracks total number of javascript used,
* helps in tracking the effect of granular chunks work
*/
userTiming({
category: 'javascript',
status: 'script count',
value: javascriptFiles.length,
})
/*
* Tracks total size of javascript used,
* helps in tracking the effect of modern/nomodern work
*/
userTiming({
category: 'javascript',
status: 'script size',
value: javascriptFiles.reduce((sum, script) => script.encodedBodySize + sum, 0),
})
}
} catch (error) {
console.error(error)
}
}, [])
}