UNPKG

1.68 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 {getBFCacheRestoreTime} from './bfcache.js';
18import {generateUniqueID} from './generateUniqueID.js';
19import {getActivationStart} from './getActivationStart.js';
20import {getNavigationEntry} from './getNavigationEntry.js';
21import {Metric} from '../types.js';
22
23export const initMetric = (name: Metric['name'], value?: number): Metric => {
24 const navEntry = getNavigationEntry();
25 let navigationType: Metric['navigationType'] = 'navigate';
26
27 if (getBFCacheRestoreTime() >= 0) {
28 navigationType = 'back-forward-cache';
29 } else if (navEntry) {
30 if (document.prerendering || getActivationStart() > 0) {
31 navigationType = 'prerender';
32 } else if (document.wasDiscarded) {
33 navigationType = 'restore';
34 } else {
35 navigationType = navEntry.type.replace(
36 /_/g,
37 '-'
38 ) as Metric['navigationType'];
39 }
40 }
41
42 return {
43 name,
44 value: typeof value === 'undefined' ? -1 : value,
45 rating: 'good', // Will be updated if the value changes.
46 delta: 0,
47 entries: [],
48 id: generateUniqueID(),
49 navigationType,
50 };
51};