UNPKG

2.83 kBPlain TextView Raw
1/*
2 * Copyright 2020 Google LLC
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * https://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17import {bindReporter} from './lib/bindReporter.js';
18import {finalMetrics} from './lib/finalMetrics.js';
19import {getFirstHidden} from './lib/getFirstHidden.js';
20import {initMetric} from './lib/initMetric.js';
21import {observe, PerformanceEntryHandler} from './lib/observe.js';
22import {onBFCacheRestore} from './lib/onBFCacheRestore.js';
23import {onHidden} from './lib/onHidden.js';
24import {firstInputPolyfill, resetFirstInputPolyfill} from './lib/polyfills/firstInputPolyfill.js';
25import {FirstInputPolyfillCallback, PerformanceEventTiming, ReportHandler} from './types.js';
26
27
28export const getFID = (onReport: ReportHandler, reportAllChanges?: boolean) => {
29 const firstHidden = getFirstHidden();
30 let metric = initMetric('FID');
31 let report: ReturnType<typeof bindReporter>;
32
33 const entryHandler = (entry: PerformanceEventTiming) => {
34 // Only report if the page wasn't hidden prior to the first input.
35 if (entry.startTime < firstHidden.timeStamp) {
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 // Prefer the native implementation if available,
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 // Only monitor bfcache restores if the browser supports FID natively.
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};