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

Refactor the stopListening() function to only run once #548

Merged
merged 2 commits into from
Oct 18, 2024
Merged
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
30 changes: 11 additions & 19 deletions src/onLCP.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,6 @@ import {LCPMetric, MetricRatingThresholds, ReportOpts} from './types.js';
/** Thresholds for LCP. See https://web.dev/articles/lcp#what_is_a_good_lcp_score */
export const LCPThresholds: MetricRatingThresholds = [2500, 4000];

const reportedMetricIDs: Record<string, boolean> = {};

/**
* Calculates the [LCP](https://web.dev/articles/lcp) value for the current page and
* calls the `callback` function once the value is ready (along with the
Expand Down Expand Up @@ -84,28 +82,23 @@ export const onLCP = (
opts!.reportAllChanges,
);

// Ensure this logic only runs once, and wrap it in an idle callback
// 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
const stopListening = () =>
whenIdleOrHidden(
runOnce(() => {
if (!reportedMetricIDs[metric.id]) {
handleEntries(po!.takeRecords() as LCPMetric['entries']);
po!.disconnect();
reportedMetricIDs[metric.id] = true;
report(true);
}
}),
);
// Ensure this logic only runs once, since it can be triggered from
// any of three different event listeners below.
const stopListening = runOnce(() => {
handleEntries(po!.takeRecords() as LCPMetric['entries']);
po!.disconnect();
report(true);
});

// Stop listening after input or visibilitychange.
// Note: while scrolling is an input that stops LCP observation, it's
// unreliable since it can be programmatically generated.
// See: https://github.com/GoogleChrome/web-vitals/issues/75
for (const type of ['keydown', 'click', 'visibilitychange']) {
addEventListener(type, () => stopListening(), {
// Wrap the listener in an idle callback so it's run in a separate
// task to reduce potential INP impact.
// https://github.com/GoogleChrome/web-vitals/issues/383
addEventListener(type, () => whenIdleOrHidden(stopListening), {
capture: true,
once: true,
});
Expand All @@ -124,7 +117,6 @@ export const onLCP = (

doubleRAF(() => {
metric.value = performance.now() - event.timeStamp;
reportedMetricIDs[metric.id] = true;
report(true);
});
});
Expand Down