UNPKG

1.46 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
17export interface PerformanceEntryHandler {
18 (entry: PerformanceEntry): void;
19}
20
21/**
22 * Takes a performance entry type and a callback function, and creates a
23 * `PerformanceObserver` instance that will observe the specified entry type
24 * with buffering enabled and call the callback _for each entry_.
25 *
26 * This function also feature-detects entry support and wraps the logic in a
27 * try/catch to avoid errors in unsupporting browsers.
28 */
29export const observe = (
30 type: string,
31 callback: PerformanceEntryHandler,
32): PerformanceObserver | undefined => {
33 try {
34 if (PerformanceObserver.supportedEntryTypes.includes(type)) {
35 const po: PerformanceObserver =
36 new PerformanceObserver((l) => l.getEntries().map(callback));
37
38 po.observe({type, buffered: true});
39 return po;
40 }
41 } catch (e) {
42 // Do nothing.
43 }
44 return;
45};