getFID.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { bindReporter } from './lib/bindReporter.js';
  2. import { getVisibilityWatcher } from './lib/getVisibilityWatcher.js';
  3. import { initMetric } from './lib/initMetric.js';
  4. import { observe } from './lib/observe.js';
  5. import { onHidden } from './lib/onHidden.js';
  6. /*
  7. * Copyright 2020 Google LLC
  8. *
  9. * Licensed under the Apache License, Version 2.0 (the "License");
  10. * you may not use this file except in compliance with the License.
  11. * You may obtain a copy of the License at
  12. *
  13. * https://www.apache.org/licenses/LICENSE-2.0
  14. *
  15. * Unless required by applicable law or agreed to in writing, software
  16. * distributed under the License is distributed on an "AS IS" BASIS,
  17. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18. * See the License for the specific language governing permissions and
  19. * limitations under the License.
  20. */
  21. /**
  22. * Calculates the [FID](https://web.dev/fid/) value for the current page and
  23. * calls the `callback` function once the value is ready, along with the
  24. * relevant `first-input` performance entry used to determine the value. The
  25. * reported value is a `DOMHighResTimeStamp`.
  26. *
  27. * _**Important:** since FID is only reported after the user interacts with the
  28. * page, it's possible that it will not be reported for some page loads._
  29. */
  30. const onFID = (onReport) => {
  31. const visibilityWatcher = getVisibilityWatcher();
  32. const metric = initMetric('FID');
  33. // eslint-disable-next-line prefer-const
  34. let report;
  35. const handleEntry = (entry) => {
  36. // Only report if the page wasn't hidden prior to the first input.
  37. if (entry.startTime < visibilityWatcher.firstHiddenTime) {
  38. metric.value = entry.processingStart - entry.startTime;
  39. metric.entries.push(entry);
  40. report(true);
  41. }
  42. };
  43. const handleEntries = (entries) => {
  44. (entries ).forEach(handleEntry);
  45. };
  46. const po = observe('first-input', handleEntries);
  47. report = bindReporter(onReport, metric);
  48. if (po) {
  49. onHidden(() => {
  50. handleEntries(po.takeRecords() );
  51. po.disconnect();
  52. }, true);
  53. }
  54. };
  55. export { onFID };
  56. //# sourceMappingURL=getFID.js.map