WEB LAB / PERFORMANCE ENGINEERING
A practical guide to finding the scripts, event handlers, and rendering work behind slow interactions—using real-user monitoring, Long Animation Frames, and targeted main-thread optimizations.
THE CORE IDEA
A page can load quickly and still feel slow. INP exposes interaction delays that happen after the initial render, while LoAF attribution helps identify the scripts and rendering work contributing to those delays. Start with field evidence, isolate the slow interaction phase, and optimize the actual bottleneck.
1. Why INP replaced First Input Delay (FID)
First Input Delay (FID) was designed to measure the delay between a user’s first qualifying interaction and the moment the browser began processing its event handlers. It was useful for identifying early input responsiveness problems, particularly when a page’s main thread was busy during startup.
But FID had a major blind spot: it measured only the first interaction’s input delay. It did not measure how long the event handlers took to execute or how long the browser needed to present the resulting visual update. A page could therefore record a good FID while later interactions—opening a dashboard panel, applying a filter, submitting a form, or expanding a complex menu—felt noticeably sluggish.
Interaction to Next Paint (INP) addresses that gap. It observes qualifying interactions throughout a page visit and measures the time from the user’s interaction until the browser presents the next frame. The reported value represents the slowest interaction, with some outlier handling for pages with many interactions.
Responsive interactions
Noticeable responsiveness risk
Slow interaction feedback
Google’s Core Web Vitals assessment uses the 75th percentile (p75) of page visits, segmented by mobile and desktop. In practice, this means at least 75% of measured visits in each device category should meet the 200 ms good threshold.
2. Understand the three phases of an interaction
Before changing JavaScript, identify where the interaction time is being spent. INP can be understood as three consecutive phases: input delay, processing duration, and presentation delay.
Phase 1: Input delay
Input delay is the time between the user’s interaction and the start of the event callbacks associated with it. It can grow when the main thread is already occupied by unrelated work.
Common causes include:
- Large JavaScript bundles being parsed, compiled, or evaluated.
- Long-running initialization tasks, analytics, or advertising scripts.
- Expensive timers, promise callbacks, or background application work running on the main thread.
- Several interactions arriving while earlier work is still blocking the event loop.
If a button’s click handler takes only 8 ms but cannot begin for 170 ms, optimizing the handler itself will not solve the main problem. You need to identify what occupied the main thread before the interaction was processed.
Phase 2: Processing duration
Processing duration covers the execution of the event callbacks associated with an interaction. A single user action can trigger multiple related events—for example, pointer, mouse, and click events. The interaction’s processing work should be considered as a group rather than treating one event entry as the entire interaction.
Typical causes include:
- Large synchronous calculations or data transformations.
- Repeated DOM queries and expensive component updates.
- Unnecessary state changes that trigger broad re-renders.
- Large event handlers that perform visual and non-visual work together.
- Repeated event listeners doing the same work.
Phase 3: Presentation delay
Presentation delay is the time between completion of the interaction’s event callbacks and the browser presenting the next frame containing the visual result.
It can be extended by:
- Expensive style recalculation and layout.
- Large DOM changes or rendering too many elements at once.
- Forced synchronous layout caused by mixing DOM reads and writes.
- Heavy work scheduled in
requestAnimationFrame()callbacks. - Rendering updates that trigger additional component or layout work.
Example: a slow dashboard filter
A user selects a filter, but the results panel appears 340 ms later.
These numbers are illustrative, not a recommended time budget. The diagnosis is clear: the main thread was busy before the filter handler began, and the handler itself also performed too much work. Reducing only the rendering cost would leave most of the delay untouched.
3. Start with production RUM, not guesswork
Real User Monitoring (RUM) records performance from actual page visits. It captures the devices, browsers, network conditions, application states, and interaction patterns that synthetic tests cannot fully reproduce.
For a high-traffic application, production data should answer more than “Is our INP poor?” It should help answer:
- Which routes or page templates have the worst p75 INP?
- Are mobile users affected more than desktop users?
- Which interaction targets are repeatedly slow?
- Is the dominant phase input delay, processing, or presentation?
- Do slow interactions correlate with a particular script, browser, device class, or release?
Instrument INP with the web-vitals attribution build
Google’s web-vitals library provides a practical way to collect Core Web Vitals in the field. Its attribution build adds diagnostic context to metric reports, including interaction timing breakdowns and related Long Animation Frame entries where available.
Install the package through your application’s normal package manager and import the attribution entry point:
import { onINP } from 'web-vitals/attribution';
onINP((metric) => {
const a = metric.attribution;
const report = {
name: metric.name,
value: metric.value,
rating: metric.rating,
id: metric.id,
interactionTarget: a?.interactionTarget ?? null,
interactionType: a?.interactionType ?? null,
inputDelay: a?.inputDelay ?? null,
processingDuration: a?.processingDuration ?? null,
presentationDelay: a?.presentationDelay ?? null,
navigationType: metric.navigationType
};
sendPerformanceReport(report);
});
The example assumes that sendPerformanceReport() is your own telemetry function. It should send a compact, validated payload to your analytics endpoint rather than serializing the entire metric object or DOM element.
Send reports without blocking the page
For a small JSON payload, navigator.sendBeacon() is useful because it is designed for sending analytics data without delaying navigation. A fetch-based fallback can use keepalive where appropriate.
function sendPerformanceReport(report) {
const endpoint = '/rum/web-vitals';
const body = new Blob(
[JSON.stringify(report)],
{ type: 'application/json' }
);
if (navigator.sendBeacon?.(endpoint, body)) {
return;
}
fetch(endpoint, {
method: 'POST',
body,
headers: {
'Content-Type': 'application/json'
},
keepalive: true,
credentials: 'same-origin'
}).catch(() => {
// Telemetry failure must not interrupt the application.
});
}
Choose useful dimensions for RUM
| Dimension | Why it matters |
|---|---|
| Route template | Finds problematic application areas without relying on raw URLs. |
| Device class | Separates mobile and desktop performance patterns. |
| Browser family | Highlights browser-specific behavior and API support. |
| Interaction target | Connects slow interactions to controls and components. |
| Interaction type | Distinguishes pointer, keyboard, and other qualifying interactions. |
| Release identifier | Helps detect regressions after deployments. |
| Phase timings | Shows which part of the interaction needs investigation. |
4. Profile slow frames with the Long Animation Frames API
The Long Tasks API can tell you that a long task occurred, but its attribution is limited. It generally does not identify the individual scripts and entry points responsible for the work.
The Long Animation Frames (LoAF) API provides a richer view. It reports rendering frames delayed beyond 50 ms and can include script-level attribution, timing information, and rendering-related measurements.
What LoAF can reveal
A LoAF entry can include:
duration: total duration of the long animation frame.blockingDuration: estimated time during which the frame was blocking the main thread from responding to high-priority work.firstUIEventTimestamp: timestamp of the first UI event queued during the frame, when present.renderStartandstyleAndLayoutStart: useful timing markers for rendering work.scripts: script timing entries that can identify the invoker, source URL, function name, and other details.
Each script entry may expose fields such as invoker, invokerType, sourceURL, sourceFunctionName, sourceCharPosition, duration, and forcedStyleAndLayoutDuration.
Feature-detect and observe LoAF entries
Do not assume every browser supports the API. Check support before registering the observer, and keep the rest of your RUM instrumentation working when LoAF is unavailable.
function observeLongAnimationFrames(onEntry) {
if (
!('PerformanceObserver' in window) ||
!PerformanceObserver.supportedEntryTypes?.includes(
'long-animation-frame'
)
) {
return null;
}
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (entry.blockingDuration < 50) continue;
onEntry({
startTime: entry.startTime,
duration: entry.duration,
blockingDuration: entry.blockingDuration,
firstUIEventTimestamp:
entry.firstUIEventTimestamp || null,
scripts: (entry.scripts || []).map((script) => ({
invoker: script.invoker || null,
invokerType: script.invokerType || null,
sourceURL: script.sourceURL || null,
sourceFunctionName:
script.sourceFunctionName || null,
sourceCharPosition:
script.sourceCharPosition ?? null,
duration: script.duration,
forcedStyleAndLayoutDuration:
script.forcedStyleAndLayoutDuration
}))
});
}
});
observer.observe({
type: 'long-animation-frame',
buffered: true
});
return observer;
}
This example filters for frames with at least 50 ms of blocking duration. Adjust the threshold to your diagnostic needs, and consider sampling or limiting the number of reports per session. A busy application can generate substantial telemetry.
Connect LoAF data to the slow INP interaction
A LoAF entry does not contain a direct identifier pointing to the INP metric that caused it. You need to correlate the timing windows. The web-vitals attribution build simplifies this: in supported versions, the INP attribution object can include related entries in longAnimationFramesEntries.
A practical RUM strategy is to report a compact summary of those entries alongside the INP attribution:
onINP((metric) => {
const a = metric.attribution;
const relatedFrames =
a?.longAnimationFramesEntries || [];
const loafSummary = relatedFrames.map((frame) => ({
startTime: frame.startTime,
duration: frame.duration,
blockingDuration: frame.blockingDuration,
scripts: (frame.scripts || []).map((script) => ({
sourceURL: script.sourceURL || null,
functionName: script.sourceFunctionName || null,
invoker: script.invoker || null,
invokerType: script.invokerType || null,
duration: script.duration,
forcedStyleAndLayoutDuration:
script.forcedStyleAndLayoutDuration
}))
}));
sendPerformanceReport({
metric: 'INP',
value: metric.value,
target: a?.interactionTarget ?? null,
inputDelay: a?.inputDelay ?? null,
processingDuration:
a?.processingDuration ?? null,
presentationDelay:
a?.presentationDelay ?? null,
loaf: loafSummary
});
});
Use the attribution to form a diagnosis
| Observation | Likely investigation |
|---|---|
| High input delay; unrelated script is active | Reduce startup work, third-party execution, and competing main-thread tasks. |
| High processing duration; app handler dominates | Profile the handler, reduce synchronous work, and split non-urgent tasks. |
| High forced style/layout time | Look for layout thrashing, repeated geometry reads, and broad DOM changes. |
| High presentation delay without obvious script cost | Inspect rendering, style recalculation, layout, paint, and frame scheduling. |
| Third-party script appears repeatedly | Test consent, loading strategy, event frequency, and whether the integration is essential. |
5. Lab testing vs. production RUM
Synthetic testing and RUM solve different problems. Neither should be treated as a complete replacement for the other.
| Area | Lab / synthetic testing | Production RUM |
|---|---|---|
| Environment | Controlled browser, device profile, and network conditions. | Real devices, browsers, networks, and application states. |
| Reproducibility | High when scripts and test conditions are consistent. | Variable because real user behavior and environments differ. |
| Interaction coverage | Only the interactions your test scripts perform. | Interactions users actually make during measured visits. |
| Root-cause analysis | Detailed traces and repeatable debugging. | Shows which real-world segments and interactions are affected. |
| Best use | Reproduce, profile, and validate a suspected issue. | Discover regressions, prioritize fixes, and verify real outcomes. |
Use field data to choose the test scenario
A Lighthouse report or a page-load-only synthetic test may not exercise the interaction that determines a page’s INP. A scripted test should reproduce the relevant user journey: open the navigation, change a filter, type into a search field, expand a panel, or submit a form.
Use Chrome DevTools’ Performance panel to record the interaction, inspect the Interactions track, and correlate the event with main-thread activity and rendering. CPU throttling can help reveal problems that are hidden on a powerful development machine.
Total Blocking Time (TBT) can help identify main-thread blocking during a load test, but it is not a substitute for INP. TBT does not measure the full range of real user interactions and their next-frame presentation.
6. Reduce input delay: keep the main thread available
Input delay often points to work that is already running when the user interacts. The objective is not simply to make the click handler faster; it is to reduce the amount of competing work that can prevent it from starting.
Reduce unnecessary JavaScript before optimizing individual functions
- Remove unused dependencies and duplicate libraries.
- Split large bundles so routes do not download and evaluate code they do not need.
- Defer non-critical initialization until it is needed.
- Load optional widgets and analytics only when their functionality is relevant.
- Audit long-running timers, observers, and repeated polling.
Yield long-running work with scheduler.yield()
JavaScript runs tasks on the main thread. A long synchronous task can prevent the browser from processing user input or updating the screen. scheduler.yield() allows a function to yield control and continue later, giving the browser an opportunity to process higher-priority work.
function yieldToMain() {
if (globalThis.scheduler?.yield) {
return scheduler.yield();
}
return new Promise((resolve) => {
setTimeout(resolve, 0);
});
}
async function processItems(items) {
const chunkSize = 100;
for (let i = 0; i < items.length; i += chunkSize) {
const chunk = items.slice(i, i + chunkSize);
processChunk(chunk);
// Allow other tasks, including user input, to run.
if (i + chunkSize < items.length) {
await yieldToMain();
}
}
}
The fallback uses a timer to schedule another task. It is not identical to the prioritized continuation behavior of scheduler.yield(), but it prevents the entire loop from executing as one uninterrupted task.
7. Reduce processing duration: slice work into smaller tasks
If an interaction handler performs data transformation, filtering, validation, or rendering preparation synchronously, it can consume the entire interaction budget. Reduce the work first; then split what remains into manageable chunks.
Separate immediate UI feedback from background work
Consider a search interface that updates a visible result count, performs expensive filtering, highlights matches, and sends analytics. Not every operation needs to finish before the user sees a response.
searchInput.addEventListener('input', (event) => {
const query = event.target.value;
// Immediate feedback.
updateSearchStatus(query);
// Non-critical work can run after the next rendering opportunity.
requestAnimationFrame(() => {
setTimeout(() => {
updateResultCount(query);
runExpensiveSearch(query);
sendSearchAnalytics(query);
}, 0);
});
});
The requestAnimationFrame() callback runs before a rendering opportunity. The timer schedules the non-critical work as a later task, allowing the browser to paint the immediate feedback first in typical circumstances.
This is a scheduling technique, not a guarantee that the deferred work will never affect later interactions. If the expensive work is still large, it can block the main thread shortly afterward. Break it into chunks, move suitable computation to a Web Worker, or reduce the work itself.
Move CPU-heavy computation off the main thread
Filtering a large dataset, parsing substantial data, or performing expensive calculations may be better suited to a Web Worker. Workers do not share the page’s DOM, so the main thread remains responsible for applying the resulting UI update.
Use workers when computation is genuinely CPU-heavy and can be separated from DOM access. Account for message serialization, data transfer, worker startup, and the time needed to apply results. Moving work to a worker does not make the computation free.
Debounce repeated work where the interaction pattern allows it
Debouncing is useful when users produce a rapid sequence of events and only the latest result matters—for example, autocomplete requests or expensive search suggestions.
let searchTimer;
searchInput.addEventListener('input', (event) => {
const query = event.target.value;
// Keep immediate input feedback responsive.
updateSearchStatus(query);
clearTimeout(searchTimer);
searchTimer = setTimeout(() => {
fetchSuggestions(query);
}, 250);
});
The 250 ms delay is an example, not a universal setting. Choose a delay that fits the interface, cancel stale requests where possible, and do not debounce actions that users expect to happen immediately, such as essential button feedback or keyboard accessibility behavior.
8. Reduce presentation delay: let the browser render efficiently
A fast event handler does not guarantee a fast interaction. After JavaScript finishes, the browser may still need to recalculate styles, perform layout, paint, and present the next frame.
Avoid forced synchronous layout
Layout thrashing occurs when code repeatedly reads layout-dependent values and then writes styles in a way that forces the browser to recalculate layout over and over.
// Avoid: interleaving layout reads and writes.
items.forEach((item) => {
const height = item.offsetHeight;
item.style.height = `${height + 10}px`;
});
// Better: read first, then write.
const heights = items.map((item) => item.offsetHeight);
items.forEach((item, index) => {
item.style.height = `${heights[index] + 10}px`;
});
The second approach reduces repeated read/write alternation. The browser may still need layout work, but batching reads and writes helps avoid forcing it repeatedly within the same task.
Use requestAnimationFrame for visual updates—not as a magic performance fix
requestAnimationFrame() schedules a callback before the browser’s next repaint. It is useful for coordinating visual updates, but placing expensive synchronous work inside that callback can delay the very paint you are trying to enable.
Keep animation-frame callbacks short. Apply the minimum visual change needed for immediate feedback, and schedule non-urgent computation separately. Do not assume that wrapping code in requestAnimationFrame() automatically moves it after the next paint.
Reduce the amount of rendering work
- Update only the components affected by the interaction.
- Avoid replacing large DOM subtrees for small state changes.
- Virtualize long lists and tables when appropriate.
- Use CSS containment where its layout and rendering implications are understood.
- Prefer transform and opacity for suitable animations instead of repeatedly changing layout properties.
- Batch DOM updates and avoid unnecessary forced style or geometry reads.
9. Control third-party scripts and event listeners
Third-party code is a common source of work that application teams do not directly control. Analytics, tag managers, chat widgets, advertising integrations, consent tools, and embedded services can all compete for main-thread time.
A script does not need to be part of your own application bundle to affect your users’ interactions. If it executes on the page’s main thread, it can contribute to input delay or presentation delay.
Audit event listener behavior
- Check whether multiple integrations attach listeners to the same high-frequency events.
- Avoid expensive synchronous work inside
click,input,keydown, and pointer event handlers. - Use event delegation where it reduces unnecessary listener registration.
- Remove listeners when widgets are destroyed or no longer active.
- Debounce or throttle non-essential work triggered by repeated events.
- Load optional scripts only when the user needs the feature, where consent and product requirements permit.
Throttle high-frequency listeners
For example, a third-party integration that performs analytics work on every resize event can schedule fewer updates:
let resizeScheduled = false;
window.addEventListener('resize', () => {
if (resizeScheduled) return;
resizeScheduled = true;
requestAnimationFrame(() => {
resizeScheduled = false;
updateNonCriticalLayoutAnalytics();
});
}, { passive: true });
This example coalesces repeated resize events into at most one callback per animation frame. It does not make the callback run after paint, and it does not guarantee a low INP by itself. The callback still needs to be inexpensive.
Use LoAF attribution to prioritize vendor work
If the same third-party source appears in slow interaction frames across many sessions, group the reports by script URL, route, device class, and interaction target. Then test whether delaying, removing, replacing, or reducing that integration improves the affected interactions.
If attribution is missing for a cross-origin script, do not conclude that the vendor is harmless. Compare traces, test with the integration disabled in a controlled environment, and review the timing of its network and execution activity.
10. A practical production INP debugging workflow
A repeatable workflow prevents teams from making broad JavaScript changes without knowing whether they are addressing the actual cause.
-
Find the affected population.
Review p75 INP by device class, route template, browser, and release. Prioritize high-traffic segments with poor responsiveness.
-
Identify the slow interaction.
Use RUM attribution to find the interaction target, interaction type, and phase breakdown. Avoid relying on an origin-wide score alone.
-
Inspect related LoAF entries.
Review blocking duration, script attribution, function entry points, and forced style/layout time. Look for recurring patterns across sessions.
-
Reproduce the interaction in the lab.
Use the same route and user journey, and test under CPU throttling or representative lower-powered devices.
-
Fix the dominant phase.
Reduce competing tasks for input delay, simplify or slice handlers for processing duration, and reduce layout/paint work for presentation delay.
-
Validate the change.
Compare controlled traces before and after the change. Confirm that the intended interaction improved without creating regressions elsewhere.
-
Monitor the production rollout.
Compare RUM distributions by release and device category. Wait for sufficient field data before declaring the issue resolved.
Prioritize by user impact, not just the slowest trace
A 900 ms interaction on a rarely used internal settings page may affect fewer people than a 350 ms interaction on a checkout control used by thousands of mobile visitors. Combine severity, frequency, business importance, and affected traffic when choosing what to fix first.
| Priority signal | What to evaluate |
|---|---|
| Severity | How far the affected segment exceeds the 200 ms good threshold. |
| Frequency | How often the slow interaction occurs. |
| Reach | How many real visits and users are affected. |
| Importance | Whether the interaction is part of a critical user journey. |
| Confidence | Whether RUM and reproducible traces support the proposed root cause. |
11. Common INP debugging mistakes
Optimizing only the first interaction
INP considers interactions throughout the visit. Test the controls users actually rely on after the page has loaded, not just the initial navigation or first click.
Treating TBT as an INP replacement
TBT is useful for diagnosing main-thread blocking in lab measurements, but it does not reproduce the full field interaction metric. Use it as supporting evidence, not as proof that INP is good.
Assuming every LoAF script is the root cause
Script attribution reports execution entry points and timing context. It is not a complete stack trace. Confirm the suspected source with a performance trace and controlled experiments.
Moving expensive work without reducing it
Deferring work can improve the immediate interaction, but the same work may block the next interaction a moment later. Reduce unnecessary work, chunk what remains, and move suitable computation off the main thread.
Using requestAnimationFrame for all deferred work
Animation-frame callbacks run before paint. Expensive work inside them can extend presentation delay. Keep them short and schedule non-critical work separately.
Ignoring mobile performance
High-end development hardware can hide main-thread bottlenecks. Segment RUM by device class and validate fixes on representative lower-powered devices.
Sending too much diagnostic data
Raw URLs, DOM content, and unrestricted script metadata can create privacy, storage, and cost problems. Collect the minimum diagnostic fields needed to identify patterns, and apply sampling and retention limits.
12. Frequently asked questions
What is a good INP score?
A good INP is 200 milliseconds or less at the 75th percentile. The assessment should be segmented between mobile and desktop visits.
Why did INP replace First Input Delay?
FID measured only the input delay of the first qualifying interaction. INP evaluates responsiveness across a page visit and includes input delay, event processing, and the time until the next frame is presented.
What is the Long Animation Frames API?
LoAF is a browser performance API that reports long rendering frames and can provide script-level attribution and rendering timing information. It helps investigate the work associated with slow interactions.
Does LoAF identify the exact function causing a slow interaction?
Not necessarily. It can report a script’s entry point, source URL, function name, and timing, but it does not provide a complete nested call stack. Use DevTools traces and controlled tests to confirm the actual bottleneck.
Can scheduler.yield() fix poor INP?
It can help break long tasks into smaller tasks so the browser can respond to input sooner. It does not eliminate unnecessary computation, fix expensive rendering, or have universal browser support. Feature-detect it and provide a fallback.
Is requestAnimationFrame good for deferring expensive JavaScript?
Not by itself. Its callback runs before the next repaint, so expensive work there can delay presentation. Use it for short visual updates and schedule non-critical work in a later task.
Can Lighthouse measure production INP?
No. Lighthouse provides controlled lab diagnostics. Production INP requires field data from real visits, such as RUM instrumentation or eligible CrUX data. Use both lab and field measurements together.
Does a good page-load score guarantee good INP?
No. A page can load quickly but become unresponsive when users interact with complex controls, large datasets, or third-party integrations. INP measures responsiveness throughout the visit.
Make responsiveness measurable before making changes
Debugging INP in a client-heavy application is not simply a matter of finding the largest JavaScript function. The delay may happen before an event handler begins, inside the handler itself, or after the handler finishes while the browser prepares the next frame.
Production RUM reveals which users and interactions are affected. LoAF adds valuable script and rendering context. Lab traces then help reproduce the problem and validate the fix. Combine those tools with smaller tasks, carefully scheduled UI updates, efficient rendering, and disciplined third-party script management.
The objective is not to make one synthetic test look faster. It is to make the interactions that matter feel responsive for real users, across the devices and conditions they actually use.
Technical references
- web.dev — Interaction to Next Paint (INP)
- web.dev — Optimize Interaction to Next Paint
- Chrome for Developers — Long Animation Frames API
- Chrome for Developers — Identify causes of poor INP
- web-vitals — Package documentation and attribution build
- MDN — Scheduler.yield()
- MDN — Long animation frame timing