getFID.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. import { bindReporter } from './lib/bindReporter.js';
  17. import { finalMetrics } from './lib/finalMetrics.js';
  18. import { getFirstHidden } from './lib/getFirstHidden.js';
  19. import { initMetric } from './lib/initMetric.js';
  20. import { observe } from './lib/observe.js';
  21. import { onBFCacheRestore } from './lib/onBFCacheRestore.js';
  22. import { onHidden } from './lib/onHidden.js';
  23. import { firstInputPolyfill, resetFirstInputPolyfill } from './lib/polyfills/firstInputPolyfill.js';
  24. export const getFID = (onReport, reportAllChanges) => {
  25. const firstHidden = getFirstHidden();
  26. let metric = initMetric('FID');
  27. let report;
  28. const entryHandler = (entry) => {
  29. // Only report if the page wasn't hidden prior to the first input.
  30. if (entry.startTime < firstHidden.timeStamp) {
  31. metric.value = entry.processingStart - entry.startTime;
  32. metric.entries.push(entry);
  33. finalMetrics.add(metric);
  34. report();
  35. }
  36. };
  37. const po = observe('first-input', entryHandler);
  38. report = bindReporter(onReport, metric, reportAllChanges);
  39. if (po) {
  40. onHidden(() => {
  41. po.takeRecords().map(entryHandler);
  42. po.disconnect();
  43. }, true);
  44. }
  45. if (self.__WEB_VITALS_POLYFILL__) {
  46. // Prefer the native implementation if available,
  47. if (!po) {
  48. window.webVitals.firstInputPolyfill(entryHandler);
  49. }
  50. onBFCacheRestore(() => {
  51. metric = initMetric('FID');
  52. report = bindReporter(onReport, metric, reportAllChanges);
  53. window.webVitals.resetFirstInputPolyfill();
  54. window.webVitals.firstInputPolyfill(entryHandler);
  55. });
  56. }
  57. else {
  58. // Only monitor bfcache restores if the browser supports FID natively.
  59. if (po) {
  60. onBFCacheRestore(() => {
  61. metric = initMetric('FID');
  62. report = bindReporter(onReport, metric, reportAllChanges);
  63. resetFirstInputPolyfill();
  64. firstInputPolyfill(entryHandler);
  65. });
  66. }
  67. }
  68. };