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.
This commit is contained in:
1 parent
b5c4dbfa56
commit
3f9de35907
1 file changed
+22
-15
+22
-15
@@ -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;
|
||||
|
||||
Reference in new issue
Block a user