getFirstHidden.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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 { onBFCacheRestore } from './onBFCacheRestore.js';
  17. import { onHidden } from './onHidden.js';
  18. let firstHiddenTime = -1;
  19. const initHiddenTime = () => {
  20. return document.visibilityState === 'hidden' ? 0 : Infinity;
  21. };
  22. const trackChanges = () => {
  23. // Update the time if/when the document becomes hidden.
  24. onHidden(({ timeStamp }) => {
  25. firstHiddenTime = timeStamp;
  26. }, true);
  27. };
  28. export const getFirstHidden = () => {
  29. if (firstHiddenTime < 0) {
  30. // If the document is hidden when this code runs, assume it was hidden
  31. // since navigation start. This isn't a perfect heuristic, but it's the
  32. // best we can do until an API is available to support querying past
  33. // visibilityState.
  34. if (self.__WEB_VITALS_POLYFILL__) {
  35. firstHiddenTime = self.webVitals.firstHiddenTime;
  36. if (firstHiddenTime === Infinity) {
  37. trackChanges();
  38. }
  39. }
  40. else {
  41. firstHiddenTime = initHiddenTime();
  42. trackChanges();
  43. }
  44. // Reset the time on bfcache restores.
  45. onBFCacheRestore(() => {
  46. // Schedule a task in order to track the `visibilityState` once it's
  47. // had an opportunity to change to visible in all browsers.
  48. // https://bugs.chromium.org/p/chromium/issues/detail?id=1133363
  49. setTimeout(() => {
  50. firstHiddenTime = initHiddenTime();
  51. trackChanges();
  52. }, 0);
  53. });
  54. }
  55. return {
  56. get timeStamp() {
  57. return firstHiddenTime;
  58. }
  59. };
  60. };