1 | /*
|
2 | * Copyright 2022 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 | import { onBFCacheRestore } from './lib/bfcache.js';
|
17 | import { bindReporter } from './lib/bindReporter.js';
|
18 | import { initMetric } from './lib/initMetric.js';
|
19 | import { DEFAULT_DURATION_THRESHOLD, processInteractionEntry, estimateP98LongestInteraction, resetInteractions, } from './lib/interactions.js';
|
20 | import { observe } from './lib/observe.js';
|
21 | import { onHidden } from './lib/onHidden.js';
|
22 | import { initInteractionCountPolyfill } from './lib/polyfills/interactionCountPolyfill.js';
|
23 | import { whenActivated } from './lib/whenActivated.js';
|
24 | import { whenIdle } from './lib/whenIdle.js';
|
25 | /** Thresholds for INP. See https://web.dev/articles/inp#what_is_a_good_inp_score */
|
26 | export const INPThresholds = [200, 500];
|
27 | /**
|
28 | * Calculates the [INP](https://web.dev/articles/inp) value for the current
|
29 | * page and calls the `callback` function once the value is ready, along with
|
30 | * the `event` performance entries reported for that interaction. The reported
|
31 | * value is a `DOMHighResTimeStamp`.
|
32 | *
|
33 | * A custom `durationThreshold` configuration option can optionally be passed to
|
34 | * control what `event-timing` entries are considered for INP reporting. The
|
35 | * default threshold is `40`, which means INP scores of less than 40 are
|
36 | * reported as 0. Note that this will not affect your 75th percentile INP value
|
37 | * unless that value is also less than 40 (well below the recommended
|
38 | * [good](https://web.dev/articles/inp#what_is_a_good_inp_score) threshold).
|
39 | *
|
40 | * If the `reportAllChanges` configuration option is set to `true`, the
|
41 | * `callback` function will be called as soon as the value is initially
|
42 | * determined as well as any time the value changes throughout the page
|
43 | * lifespan.
|
44 | *
|
45 | * _**Important:** INP should be continually monitored for changes throughout
|
46 | * the entire lifespan of a page—including if the user returns to the page after
|
47 | * it's been hidden/backgrounded. However, since browsers often [will not fire
|
48 | * additional callbacks once the user has backgrounded a
|
49 | * page](https://developer.chrome.com/blog/page-lifecycle-api/#advice-hidden),
|
50 | * `callback` is always called when the page's visibility state changes to
|
51 | * hidden. As a result, the `callback` function might be called multiple times
|
52 | * during the same page load._
|
53 | */
|
54 | export const onINP = (onReport, opts) => {
|
55 | // Return if the browser doesn't support all APIs needed to measure INP.
|
56 | if (!('PerformanceEventTiming' in self &&
|
57 | 'interactionId' in PerformanceEventTiming.prototype)) {
|
58 | return;
|
59 | }
|
60 | // Set defaults
|
61 | opts = opts || {};
|
62 | whenActivated(() => {
|
63 | // TODO(philipwalton): remove once the polyfill is no longer needed.
|
64 | initInteractionCountPolyfill();
|
65 | let metric = initMetric('INP');
|
66 | let report;
|
67 | const handleEntries = (entries) => {
|
68 | // Queue the `handleEntries()` callback in the next idle task.
|
69 | // This is needed to increase the chances that all event entries that
|
70 | // occurred between the user interaction and the next paint
|
71 | // have been dispatched. Note: there is currently an experiment
|
72 | // running in Chrome (EventTimingKeypressAndCompositionInteractionId)
|
73 | // 123+ that if rolled out fully may make this no longer necessary.
|
74 | whenIdle(() => {
|
75 | entries.forEach(processInteractionEntry);
|
76 | const inp = estimateP98LongestInteraction();
|
77 | if (inp && inp.latency !== metric.value) {
|
78 | metric.value = inp.latency;
|
79 | metric.entries = inp.entries;
|
80 | report();
|
81 | }
|
82 | });
|
83 | };
|
84 | const po = observe('event', handleEntries, {
|
85 | // Event Timing entries have their durations rounded to the nearest 8ms,
|
86 | // so a duration of 40ms would be any event that spans 2.5 or more frames
|
87 | // at 60Hz. This threshold is chosen to strike a balance between usefulness
|
88 | // and performance. Running this callback for any interaction that spans
|
89 | // just one or two frames is likely not worth the insight that could be
|
90 | // gained.
|
91 | durationThreshold: opts.durationThreshold ?? DEFAULT_DURATION_THRESHOLD,
|
92 | });
|
93 | report = bindReporter(onReport, metric, INPThresholds, opts.reportAllChanges);
|
94 | if (po) {
|
95 | // Also observe entries of type `first-input`. This is useful in cases
|
96 | // where the first interaction is less than the `durationThreshold`.
|
97 | po.observe({ type: 'first-input', buffered: true });
|
98 | onHidden(() => {
|
99 | handleEntries(po.takeRecords());
|
100 | report(true);
|
101 | });
|
102 | // Only report after a bfcache restore if the `PerformanceObserver`
|
103 | // successfully registered.
|
104 | onBFCacheRestore(() => {
|
105 | resetInteractions();
|
106 | metric = initMetric('INP');
|
107 | report = bindReporter(onReport, metric, INPThresholds, opts.reportAllChanges);
|
108 | });
|
109 | }
|
110 | });
|
111 | };
|