Performance Observer API
You'll learn how to monitor performance metrics asynchronously and automatically as they happen in the browser.
What Is the Performance Observer API?
Instead of repeatedly polling performance.getEntries() to check for new performance data, the Performance Observer API lets you subscribe to performance metrics. The browser notifies you whenever new entries are recorded—like navigation timing, resource loads, or custom marks—without you having to constantly ask for them.
Think of it like setting up a doorbell notification instead of repeatedly checking the door to see if someone's arrived.
How It Works
You create a PerformanceObserver object with a callback function, then tell it which entry types you want to observe:
// Create an observer
const observer = new PerformanceObserver((list) => {
// Called automatically when new entries arrive
const entries = list.getEntries();
entries.forEach((entry) => {
console.log(`${entry.name}: ${entry.duration}ms`);
// Send to analytics, log, or process
});
});
// Start observing specific entry types
observer.observe({
entryTypes: ['navigation', 'resource', 'measure']
});
The observer fires your callback whenever the browser records matching performance entries. You can observe navigation timing, resource timing, user timing (marks/measures), and more—all automatically.
To stop observing:
observer.disconnect();
Why Use Performance Observer?
This API is asynchronous and event-driven, making it ideal for Real User Monitoring (RUM). You capture metrics as they occur without blocking the main thread or missing data that arrives after your script runs. It's the modern, efficient way to collect performance data in production.
Key Takeaway: Performance Observer API lets you subscribe to performance metrics asynchronously, automatically capturing data as it's recorded without polling or blocking execution.