Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make event handlers that are only needed to run once, to only run once #537

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions src/lib/onHidden.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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},
);
};
2 changes: 1 addition & 1 deletion src/lib/whenIdle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export const whenIdle = (cb: () => void): number => {
cb();
} else {
handle = rIC(cb);
onHidden(cb);
onHidden(cb, true);
}
return handle;
};
7 changes: 5 additions & 2 deletions src/onLCP.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down