Interaction to Next Paint (INP) Optimization Fix
In this tutorial, you'll learn about Interaction to Next Paint (INP) Optimization Fix. We cover key concepts, practical examples, and best practices.
The Problem
Interaction to Next Paint (INP) measures the time from when a user interacts with the page (click, keypress, tap) until the browser paints the next visual update. High INP makes the app feel unresponsive. INP replaces First Input Delay (FID) as a Core Web Vital in March 2024.
Quick Fix
Step 1: Measure INP in the field
// Wrong — guessing INP values
// Right — use PerformanceObserver
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
console.log('Interaction:', {
target: entry.target,
type: entry.entryType,
interactionId: entry.interactionId,
duration: entry.duration
});
}
});
observer.observe({ type: 'interaction', buffered: true });
// Report INP at page unload
window.addEventListener('beforeunload', () => {
const entries = performance.getEntriesByType('interaction');
if (entries.length > 0) {
const inp = Math.max(...entries.map(e => e.duration));
console.log('Page INP:', inp);
// Send to analytics
}
});
Step 2: Avoid long tasks during interaction
// Wrong — heavy computation blocks interaction handler
button.addEventListener('click', () => {
const data = [];
for (let i = 0; i < 100000; i++) {
data.push(expensiveCalculation(i));
}
updateUI(data);
});
// Right — defer computation, show immediate feedback
button.addEventListener('click', (e) => {
// Show immediate visual feedback
e.target.classList.add('pressed');
e.target.textContent = 'Processing...';
// Defer heavy work
setTimeout(() => {
const data = [];
for (let i = 0; i < 100000; i++) {
data.push(expensiveCalculation(i));
}
requestAnimationFrame(() => {
updateUI(data);
e.target.classList.remove('pressed');
e.target.textContent = 'Done';
});
}, 50);
});
Step 3: Use passive event listeners
// Wrong — event listener may block scroll
document.addEventListener('touchstart', handler);
// Right — passive listener does not block scrolling
document.addEventListener('touchstart', handler, { passive: true });
// Only use preventDefault when necessary
document.addEventListener('touchstart', (e) => {
if (shouldPrevent(e)) {
e.preventDefault(); // Will warn if passive
}
}, { passive: false });
Step 4: Defer non-interaction work
// Wrong — all scripts run on load, competing with interactions
window.addEventListener('load', () => {
setupAnalytics();
loadNonCriticalWidgets();
prefetchNextPage();
});
// Right — prioritize interaction readiness
// Critical: load first
loadAppShell();
// Non-critical: defer
if ('requestIdleCallback' in window) {
requestIdleCallback(setupAnalytics, { timeout: 5000 });
requestIdleCallback(loadNonCriticalWidgets, { timeout: 10000 });
} else {
setTimeout(setupAnalytics, 2000);
setTimeout(loadNonCriticalWidgets, 4000);
}
Step 5: Optimize event handler performance
// Wrong — expensive DOM read/write in handler
function onInputChange(e) {
const items = document.querySelectorAll('.item'); // DOM read
items.forEach(item => {
item.style.padding = '10px'; // DOM write
});
}
// Right — batch DOM operations
function onInputChange(e) {
const newPadding = calculatePadding(e.target.value);
requestAnimationFrame(() => {
const items = document.querySelectorAll('.item');
items.forEach(item => {
item.style.padding = newPadding + 'px';
});
});
}
Prevention
- Monitor INP using PerformanceObserver in production
- Keep interaction handlers under 50ms total
- Use
setTimeoutorscheduler.postTaskto defer non-critical work after interaction - Use passive event listeners for scroll and touch events
- Batch DOM reads and writes separately to avoid layout thrashing
Common Mistakes with inp interaction
- Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
These mistakes appear frequently in real-world PERF code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro