diff --git a/src/lib/onHidden.ts b/src/lib/onHidden.ts index f59d4c90..56813cd3 100644 --- a/src/lib/onHidden.ts +++ b/src/lib/onHidden.ts @@ -14,10 +14,14 @@ * limitations under the License. */ -export const onHidden = (cb: () => void) => { - document.addEventListener('visibilitychange', () => { - if (document.visibilityState === 'hidden') { - cb(); - } - }); +export const onHidden = (cb: () => void, once: boolean = false) => { + document.addEventListener( + 'visibilitychange', + () => { + if (document.visibilityState === 'hidden') { + cb(); + } + }, + {once: once}, + ); }; diff --git a/src/lib/whenIdle.ts b/src/lib/whenIdle.ts index d63b399a..dbf6dcdd 100644 --- a/src/lib/whenIdle.ts +++ b/src/lib/whenIdle.ts @@ -32,7 +32,7 @@ export const whenIdle = (cb: () => void): number => { cb(); } else { handle = rIC(cb); - onHidden(cb); + onHidden(cb, true); } return handle; }; diff --git a/src/onLCP.ts b/src/onLCP.ts index 68557711..034ccbdb 100644 --- a/src/onLCP.ts +++ b/src/onLCP.ts @@ -101,10 +101,13 @@ export const onLCP = ( // Wrap in a setTimeout so the callback is run in a separate task // to avoid extending the keyboard/click handler to reduce INP impact // https://github.com/GoogleChrome/web-vitals/issues/383 - addEventListener(type, () => whenIdle(stopListening), true); + addEventListener(type, () => whenIdle(stopListening), { + once: true, + capture: true, + }); } - onHidden(stopListening); + onHidden(stopListening, true); // Only report after a bfcache restore if the `PerformanceObserver` // successfully registered.