CodeBlanks Logo Icon CodeBlanks

PerformanceObserver

JavaScript course · Expert · Lesson 13/63

Learn to observe performance entries with PerformanceObserver.

PerformanceObserver

PerformanceObserver collects performance entries in modern browsers. Instead of measuring each step with performance.now, you listen to the entries the browser already produces. Many types exist: paint timing, resource loading and user timing (mark, measure).

You first write a callback; it receives a list and you loop through list.getEntries(). Then you create the observer with new PerformanceObserver(callback) and tell it which types to watch with observer.observe({ entryTypes: [...] }). When done, call disconnect.

buffered, takeRecords and disconnect

PerformanceObserver offers a few extras. Add buffered: true to observe and the entries buffered since page load arrive too, so you do not miss important data when you start late.

To grab pending entries at once, call takeRecords; it returns everything queued and clears the list. To stop the observer, call observer.disconnect(); this prevents memory leaks and keeps things clean even when the page stays open.

Exercise Watch paint entries

Create a PerformanceObserver. The callback takes list; for each entry log entry.name to the console. Pass 'paint' as the entryTypes value and start with observe.

Show example solution
1. Create with new PerformanceObserver((list) => {...}).
2. Loop through list.getEntries() and log entry.name.
3. Start with observer.observe({ entryTypes: ['paint'] }).

Example solution:
const observer = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    console.log(entry.name);
  }
});
observer.observe({ entryTypes: ['paint'] });

Test yourself

  1. What does the entryTypes option given to observe decide?

    • The name of the observer
    • Which performance entry types are watched
    • How many times the callback runs
    • When the observer is disconnected
    Show answer

    Which performance entry types are watched — Correct. The entryTypes array tells which entry types to listen to, like paint, resource or measure.

  2. Add the entryTypes array

    observer.observe({ entryTypes:____});
    Show answer
    observer.observe({ entryTypes:['paint']});
  3. Match PerformanceEntry fields

    name
    Entry name
    entryType
    Entry type
    startTime
    Start time
    duration
    Duration

All lessons in Expert