1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | import {onBFCacheRestore} from './lib/bfcache.js';
|
18 | import {bindReporter} from './lib/bindReporter.js';
|
19 | import {getVisibilityWatcher} from './lib/getVisibilityWatcher.js';
|
20 | import {initMetric} from './lib/initMetric.js';
|
21 | import {observe} from './lib/observe.js';
|
22 | import {onHidden} from './lib/onHidden.js';
|
23 | import {
|
24 | firstInputPolyfill,
|
25 | resetFirstInputPolyfill,
|
26 | } from './lib/polyfills/firstInputPolyfill.js';
|
27 | import {runOnce} from './lib/runOnce.js';
|
28 | import {whenActivated} from './lib/whenActivated.js';
|
29 | import {
|
30 | FIDMetric,
|
31 | FirstInputPolyfillCallback,
|
32 | MetricRatingThresholds,
|
33 | ReportOpts,
|
34 | } from './types.js';
|
35 |
|
36 |
|
37 | export const FIDThresholds: MetricRatingThresholds = [100, 300];
|
38 |
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 |
|
45 |
|
46 |
|
47 |
|
48 | export const onFID = (
|
49 | onReport: (metric: FIDMetric) => void,
|
50 | opts?: ReportOpts,
|
51 | ) => {
|
52 |
|
53 | opts = opts || {};
|
54 |
|
55 | whenActivated(() => {
|
56 | const visibilityWatcher = getVisibilityWatcher();
|
57 | let metric = initMetric('FID');
|
58 | let report: ReturnType<typeof bindReporter>;
|
59 |
|
60 | const handleEntry = (entry: PerformanceEventTiming) => {
|
61 |
|
62 | if (entry.startTime < visibilityWatcher.firstHiddenTime) {
|
63 | metric.value = entry.processingStart - entry.startTime;
|
64 | metric.entries.push(entry);
|
65 | report(true);
|
66 | }
|
67 | };
|
68 |
|
69 | const handleEntries = (entries: FIDMetric['entries']) => {
|
70 | entries.forEach(handleEntry);
|
71 | };
|
72 |
|
73 | const po = observe('first-input', handleEntries);
|
74 |
|
75 | report = bindReporter(
|
76 | onReport,
|
77 | metric,
|
78 | FIDThresholds,
|
79 | opts!.reportAllChanges,
|
80 | );
|
81 |
|
82 | if (po) {
|
83 | onHidden(
|
84 | runOnce(() => {
|
85 | handleEntries(po.takeRecords() as FIDMetric['entries']);
|
86 | po.disconnect();
|
87 | }),
|
88 | );
|
89 |
|
90 | onBFCacheRestore(() => {
|
91 | metric = initMetric('FID');
|
92 | report = bindReporter(
|
93 | onReport,
|
94 | metric,
|
95 | FIDThresholds,
|
96 | opts!.reportAllChanges,
|
97 | );
|
98 |
|
99 |
|
100 | resetFirstInputPolyfill();
|
101 | firstInputPolyfill(handleEntry as FirstInputPolyfillCallback);
|
102 | });
|
103 | }
|
104 | });
|
105 | };
|