1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | import {bindReporter} from './lib/bindReporter.js';
|
18 | import {finalMetrics} from './lib/finalMetrics.js';
|
19 | import {getVisibilityWatcher} from './lib/getVisibilityWatcher.js';
|
20 | import {initMetric} from './lib/initMetric.js';
|
21 | import {observe, PerformanceEntryHandler} from './lib/observe.js';
|
22 | import {onBFCacheRestore} from './lib/onBFCacheRestore.js';
|
23 | import {onHidden} from './lib/onHidden.js';
|
24 | import {firstInputPolyfill, resetFirstInputPolyfill} from './lib/polyfills/firstInputPolyfill.js';
|
25 | import {FirstInputPolyfillCallback, PerformanceEventTiming, ReportHandler} from './types.js';
|
26 |
|
27 |
|
28 | export const getFID = (onReport: ReportHandler, reportAllChanges?: boolean) => {
|
29 | const visibilityWatcher = getVisibilityWatcher();
|
30 | let metric = initMetric('FID');
|
31 | let report: ReturnType<typeof bindReporter>;
|
32 |
|
33 | const entryHandler = (entry: PerformanceEventTiming) => {
|
34 |
|
35 | if (entry.startTime < visibilityWatcher.firstHiddenTime) {
|
36 | metric.value = entry.processingStart - entry.startTime;
|
37 | metric.entries.push(entry);
|
38 | finalMetrics.add(metric);
|
39 | report();
|
40 | }
|
41 | };
|
42 |
|
43 | const po = observe('first-input', entryHandler as PerformanceEntryHandler);
|
44 | report = bindReporter(onReport, metric, reportAllChanges);
|
45 |
|
46 | if (po) {
|
47 | onHidden(() => {
|
48 | po.takeRecords().map(entryHandler as PerformanceEntryHandler);
|
49 | po.disconnect();
|
50 | }, true);
|
51 | }
|
52 |
|
53 | if (self.__WEB_VITALS_POLYFILL__) {
|
54 |
|
55 | if (!po) {
|
56 | window.webVitals.firstInputPolyfill(entryHandler as FirstInputPolyfillCallback)
|
57 | }
|
58 | onBFCacheRestore(() => {
|
59 | metric = initMetric('FID');
|
60 | report = bindReporter(onReport, metric, reportAllChanges);
|
61 | window.webVitals.resetFirstInputPolyfill();
|
62 | window.webVitals.firstInputPolyfill(entryHandler as FirstInputPolyfillCallback);
|
63 | });
|
64 | } else {
|
65 |
|
66 | if (po) {
|
67 | onBFCacheRestore(() => {
|
68 | metric = initMetric('FID');
|
69 | report = bindReporter(onReport, metric, reportAllChanges);
|
70 | resetFirstInputPolyfill();
|
71 | firstInputPolyfill(entryHandler as FirstInputPolyfillCallback);
|
72 | });
|
73 | }
|
74 | }
|
75 | };
|