The Long Tasks API
You'll learn how to programmatically detect and measure long tasks in your web application using JavaScript's PerformanceObserver API.
What Is the Long Tasks API?
While DevTools helps you see long tasks visually, the Long Tasks API lets your JavaScript code detect them automatically in real users' browsers. Think of it like installing a security camera that alerts you whenever something blocks the main thread for too long—instead of manually watching for problems, the browser tells your code when they happen.
Using PerformanceObserver to Catch Long Tasks
The PerformanceObserver watches for performance events. To monitor long tasks, you create an observer that listens for the "longtask" entry type:
// Create an observer to watch for long tasks
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
console.log('Long task detected!');
console.log('Duration:', entry.duration, 'ms');
console.log('Start time:', entry.startTime, 'ms');
console.log('Name:', entry.name);
// Attribution tells you what caused it
if (entry.attribution && entry.attribution.length > 0) {
console.log('Container type:', entry.attribution[0].containerType);
console.log('Container name:', entry.attribution[0].containerName);
}
}
});
// Start observing long tasks
observer.observe({ entryTypes: ['longtask'] });
What You Get
Each long task entry provides:
- duration: How long it blocked the thread (always ≥50ms)
- startTime: When it began
- attribution: Context about what caused it (script, frame, etc.)
This lets you send real-world performance data to your analytics, helping you catch issues DevTools might miss.
Key Takeaway: The Long Tasks API uses PerformanceObserver to automatically detect blocking tasks in production, providing duration and attribution data you can log or send to monitoring services.