From 3f9de35907b70642e1c894e91e4ab2fe1e1c0d47 Mon Sep 17 00:00:00 2001 From: Stanislaw <56738034+anvme@users.noreply.github.com> Date: Thu, 7 May 2026 15:31:49 +0200 Subject: [PATCH] perf(tracker): defer INP percentile computation to flush time The INP observer sorted Object.values(interactions) on every event entry, even though metrics.inp is only read when sendPerformance() flushes. Defer the sort + p98 computation to flush, and drain queued observer entries via observer.takeRecords() to capture the most recent interactions on pagehide/visibilitychange. Output is identical (same INP value computed). Savings are largest on interaction-heavy pages and low-end devices where the per-event sort compounds. --- src/tracker/index.js | 37 ++++++++++++++++++++++--------------- 1 file changed, 22 insertions(+), 15 deletions(-) diff --git a/src/tracker/index.js b/src/tracker/index.js index 521a1f717..2df5ccded 100644 --- a/src/tracker/index.js +++ b/src/tracker/index.js @@ -292,27 +292,33 @@ // INP - group by interactionId, 98th percentile, 40ms threshold let interactions = {}; - try { - const observer = new PerformanceObserver(list => { - list.getEntries().forEach(entry => { - if (entry.interactionId) { - const existing = interactions[entry.interactionId]; - if (!existing || entry.duration > existing) { - interactions[entry.interactionId] = entry.duration; - } - const values = Object.values(interactions).sort((a, b) => b - a); - if (values.length) { - const p98Index = Math.floor(Math.max(values.length, 10) * 0.02); - metrics.inp = values[Math.min(p98Index, values.length - 1)]; - } + let inpObserver; + const recordInteractions = entries => { + entries.forEach(entry => { + if (entry.interactionId) { + const existing = interactions[entry.interactionId]; + if (!existing || entry.duration > existing) { + interactions[entry.interactionId] = entry.duration; } - }); + } }); - observer.observe({ type: 'event', buffered: true, durationThreshold: 40 }); + }; + try { + inpObserver = new PerformanceObserver(list => recordInteractions(list.getEntries())); + inpObserver.observe({ type: 'event', buffered: true, durationThreshold: 40 }); } catch { /* not supported */ } + const computeInp = () => { + if (inpObserver) recordInteractions(inpObserver.takeRecords()); + const values = Object.values(interactions).sort((a, b) => b - a); + if (values.length) { + const p98Index = Math.floor(Math.max(values.length, 10) * 0.02); + metrics.inp = values[Math.min(p98Index, values.length - 1)]; + } + }; + const getEntriesByType = type => { try { return window.performance?.getEntriesByType?.(type) || []; @@ -353,6 +359,7 @@ if (sent) return; applyFallbackMetrics(); + computeInp(); metrics.duration = Math.round(performance.now() - pageStartTime); sent = true;