Summary - Observers and channels
Build a multi-tab metrics collection demo with PerformanceObserver and BroadcastChannel.
Summary - Observers and channels
In this group you learned modern observer and channel APIs:
- PerformanceObserver: collects performance entries
- ResizeObserver: reports element size changes, with
contentBoxSizeandborderBoxSize - ReportingObserver: catches browser reports (deprecation, intervention)
- BroadcastChannel: carries messages across same-origin tabs
- MessageChannel: builds a one-to-one channel between two ports
They share a callback based design; their observers start with observe and end with disconnect.
Exercise Watch resource entries
Create a PerformanceObserver. The callback takes list; for each entry log entry.entryType to the console. Pass 'resource' 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.entryType.
3. Start with observer.observe({ entryTypes: ['resource'] }).
Example solution:
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
console.log(entry.entryType);
}
});
observer.observe({ entryTypes: ['resource'] });
Which API when?
The right API depends on your need:
- To measure page speed, use PerformanceObserver
- To react to an element's layout changes, use ResizeObserver
- To collect browser warnings, use ReportingObserver
- For instant messages across tabs, use BroadcastChannel
- For a dedicated channel between two endpoints, use MessageChannel
The wrong choice adds complexity; the right choice does more with less code.
Exercise Listen for messages on the logs channel
Create a BroadcastChannel named 'logs'. Use onmessage to log the incoming event.data to the console.
Show example solution
1. Create the channel with const channel = new BroadcastChannel('logs').
2. Listen with channel.onmessage = (event) => console.log(event.data).
Example solution:
const channel = new BroadcastChannel('logs');
channel.onmessage = (event) => {
console.log(event.data);
};
Test yourself
-
Which API is best for cross-tab messaging between same-origin tabs?
- BroadcastChannel
- MessageChannel
- ResizeObserver
- ReportingObserver
Show answer
BroadcastChannel — Correct. BroadcastChannel is designed for messaging between same-origin tabs.
-
Match APIs to use cases
- PerformanceObserver
- Timing metrics
- ResizeObserver
- Size changes
- BroadcastChannel
- Cross-tab messages
- MessageChannel
- Port-to-port messages