observe.js 1.5 KB

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