UNPKG

3.07 kBJavaScriptView 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 */
16import { onBFCacheRestore } from './lib/bfcache.js';
17import { bindReporter } from './lib/bindReporter.js';
18import { getVisibilityWatcher } from './lib/getVisibilityWatcher.js';
19import { initMetric } from './lib/initMetric.js';
20import { observe } from './lib/observe.js';
21import { onHidden } from './lib/onHidden.js';
22import { firstInputPolyfill, resetFirstInputPolyfill, } from './lib/polyfills/firstInputPolyfill.js';
23import { runOnce } from './lib/runOnce.js';
24import { whenActivated } from './lib/whenActivated.js';
25/** Thresholds for FID. See https://web.dev/articles/fid#what_is_a_good_fid_score */
26export const FIDThresholds = [100, 300];
27/**
28 * Calculates the [FID](https://web.dev/articles/fid) value for the current page and
29 * calls the `callback` function once the value is ready, along with the
30 * relevant `first-input` performance entry used to determine the value. The
31 * reported value is a `DOMHighResTimeStamp`.
32 *
33 * _**Important:** since FID is only reported after the user interacts with the
34 * page, it's possible that it will not be reported for some page loads._
35 */
36export const onFID = (onReport, opts) => {
37 // Set defaults
38 opts = opts || {};
39 whenActivated(() => {
40 const visibilityWatcher = getVisibilityWatcher();
41 let metric = initMetric('FID');
42 let report;
43 const handleEntry = (entry) => {
44 // Only report if the page wasn't hidden prior to the first input.
45 if (entry.startTime < visibilityWatcher.firstHiddenTime) {
46 metric.value = entry.processingStart - entry.startTime;
47 metric.entries.push(entry);
48 report(true);
49 }
50 };
51 const handleEntries = (entries) => {
52 entries.forEach(handleEntry);
53 };
54 const po = observe('first-input', handleEntries);
55 report = bindReporter(onReport, metric, FIDThresholds, opts.reportAllChanges);
56 if (po) {
57 onHidden(runOnce(() => {
58 handleEntries(po.takeRecords());
59 po.disconnect();
60 }));
61 onBFCacheRestore(() => {
62 metric = initMetric('FID');
63 report = bindReporter(onReport, metric, FIDThresholds, opts.reportAllChanges);
64 // Browsers don't re-emit FID on bfcache restore so fake it until you make it
65 resetFirstInputPolyfill();
66 firstInputPolyfill(handleEntry);
67 });
68 }
69 });
70};