observe.ts 1.6 KB

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