UNPKG

4.04 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 {initMetric} from './lib/initMetric.js';
19import {onBFCacheRestore} from './lib/bfcache.js';
20import {getNavigationEntry} from './lib/getNavigationEntry.js';
21import {ReportCallback, ReportOpts} from './types.js';
22import {getActivationStart} from './lib/getActivationStart.js';
23import {whenActivated} from './lib/whenActivated.js';
24
25/**
26 * Runs in the next task after the page is done loading and/or prerendering.
27 * @param callback
28 */
29const whenReady = (callback: () => void) => {
30 if (document.prerendering) {
31 whenActivated(() => whenReady(callback));
32 } else if (document.readyState !== 'complete') {
33 addEventListener('load', () => whenReady(callback), true);
34 } else {
35 // Queue a task so the callback runs after `loadEventEnd`.
36 setTimeout(callback, 0);
37 }
38};
39
40/**
41 * Calculates the [TTFB](https://web.dev/time-to-first-byte/) value for the
42 * current page and calls the `callback` function once the page has loaded,
43 * along with the relevant `navigation` performance entry used to determine the
44 * value. The reported value is a `DOMHighResTimeStamp`.
45 *
46 * Note, this function waits until after the page is loaded to call `callback`
47 * in order to ensure all properties of the `navigation` entry are populated.
48 * This is useful if you want to report on other metrics exposed by the
49 * [Navigation Timing API](https://w3c.github.io/navigation-timing/). For
50 * example, the TTFB metric starts from the page's [time
51 * origin](https://www.w3.org/TR/hr-time-2/#sec-time-origin), which means it
52 * includes time spent on DNS lookup, connection negotiation, network latency,
53 * and server processing time.
54 */
55export const onTTFB = (onReport: ReportCallback, opts?: ReportOpts) => {
56 // Set defaults
57 opts = opts || {};
58
59 // https://web.dev/ttfb/#what-is-a-good-ttfb-score
60 const thresholds = [800, 1800];
61
62 let metric = initMetric('TTFB');
63 let report = bindReporter(
64 onReport,
65 metric,
66 thresholds,
67 opts.reportAllChanges
68 );
69
70 whenReady(() => {
71 const navEntry = getNavigationEntry();
72
73 if (navEntry) {
74 const responseStart = navEntry.responseStart;
75
76 // In some cases no value is reported by the browser (for
77 // privacy/security reasons), and in other cases (bugs) the value is
78 // negative or is larger than the current page time. Ignore these cases:
79 // https://github.com/GoogleChrome/web-vitals/issues/137
80 // https://github.com/GoogleChrome/web-vitals/issues/162
81 // https://github.com/GoogleChrome/web-vitals/issues/275
82 if (responseStart <= 0 || responseStart > performance.now()) return;
83
84 // The activationStart reference is used because TTFB should be
85 // relative to page activation rather than navigation start if the
86 // page was prerendered. But in cases where `activationStart` occurs
87 // after the first byte is received, this time should be clamped at 0.
88 metric.value = Math.max(responseStart - getActivationStart(), 0);
89
90 metric.entries = [navEntry];
91 report(true);
92
93 // Only report TTFB after bfcache restores if a `navigation` entry
94 // was reported for the initial load.
95 onBFCacheRestore(() => {
96 metric = initMetric('TTFB', 0);
97 report = bindReporter(
98 onReport,
99 metric,
100 thresholds,
101 opts!.reportAllChanges
102 );
103
104 report(true);
105 });
106 }
107 });
108};