UNPKG

3.99 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 {onBFCacheRestore} from './lib/bfcache.js';
18import {bindReporter} from './lib/bindReporter.js';
19import {getVisibilityWatcher} from './lib/getVisibilityWatcher.js';
20import {initMetric} from './lib/initMetric.js';
21import {observe} from './lib/observe.js';
22import {onHidden} from './lib/onHidden.js';
23import {
24 firstInputPolyfill,
25 resetFirstInputPolyfill,
26} from './lib/polyfills/firstInputPolyfill.js';
27import {runOnce} from './lib/runOnce.js';
28import {whenActivated} from './lib/whenActivated.js';
29import {
30 FIDMetric,
31 FirstInputPolyfillCallback,
32 ReportCallback,
33 ReportOpts,
34} from './types.js';
35
36/**
37 * Calculates the [FID](https://web.dev/fid/) value for the current page and
38 * calls the `callback` function once the value is ready, along with the
39 * relevant `first-input` performance entry used to determine the value. The
40 * reported value is a `DOMHighResTimeStamp`.
41 *
42 * _**Important:** since FID is only reported after the user interacts with the
43 * page, it's possible that it will not be reported for some page loads._
44 */
45export const onFID = (onReport: ReportCallback, opts?: ReportOpts) => {
46 // Set defaults
47 opts = opts || {};
48
49 whenActivated(() => {
50 // https://web.dev/fid/#what-is-a-good-fid-score
51 const thresholds = [100, 300];
52
53 const visibilityWatcher = getVisibilityWatcher();
54 let metric = initMetric('FID');
55 let report: ReturnType<typeof bindReporter>;
56
57 const handleEntry = (entry: PerformanceEventTiming) => {
58 // Only report if the page wasn't hidden prior to the first input.
59 if (entry.startTime < visibilityWatcher.firstHiddenTime) {
60 metric.value = entry.processingStart - entry.startTime;
61 metric.entries.push(entry);
62 report(true);
63 }
64 };
65
66 const handleEntries = (entries: FIDMetric['entries']) => {
67 (entries as PerformanceEventTiming[]).forEach(handleEntry);
68 };
69
70 const po = observe('first-input', handleEntries);
71 report = bindReporter(onReport, metric, thresholds, opts!.reportAllChanges);
72
73 if (po) {
74 onHidden(
75 runOnce(() => {
76 handleEntries(po.takeRecords() as FIDMetric['entries']);
77 po.disconnect();
78 })
79 );
80 }
81
82 if (window.__WEB_VITALS_POLYFILL__) {
83 console.warn(
84 'The web-vitals "base+polyfill" build is deprecated. See: https://bit.ly/3aqzsGm'
85 );
86
87 // Prefer the native implementation if available,
88 if (!po) {
89 window.webVitals.firstInputPolyfill(
90 handleEntry as FirstInputPolyfillCallback
91 );
92 }
93 onBFCacheRestore(() => {
94 metric = initMetric('FID');
95 report = bindReporter(
96 onReport,
97 metric,
98 thresholds,
99 opts!.reportAllChanges
100 );
101
102 window.webVitals.resetFirstInputPolyfill();
103 window.webVitals.firstInputPolyfill(
104 handleEntry as FirstInputPolyfillCallback
105 );
106 });
107 } else {
108 // Only monitor bfcache restores if the browser supports FID natively.
109 if (po) {
110 onBFCacheRestore(() => {
111 metric = initMetric('FID');
112 report = bindReporter(
113 onReport,
114 metric,
115 thresholds,
116 opts!.reportAllChanges
117 );
118
119 resetFirstInputPolyfill();
120 firstInputPolyfill(handleEntry as FirstInputPolyfillCallback);
121 });
122 }
123 }
124 });
125};