Using Browser Observer APIs: IntersectionObserver, MutationObserver, ResizeObserver, PerformanceObserver, and ReportingObserver
This article explains how to use the five browser Observer APIs—IntersectionObserver, MutationObserver, ResizeObserver, PerformanceObserver, and ReportingObserver—to monitor element visibility, attribute changes, size adjustments, performance metrics, and browser interventions, providing code examples and practical use cases.
In modern web development, handling user interactions with addEventListener is common, but many changes are not directly triggered by users, such as element visibility, size, attribute modifications, and performance events. Browsers provide five Observer APIs to monitor these changes.
IntersectionObserver
IntersectionObserver watches the intersection ratio between an element and the viewport, triggering callbacks when specified thresholds are reached. The article demonstrates creating two boxes at different scroll positions and observing them with thresholds of 0.5 and 1, logging when each becomes half-visible or fully visible.
<div id="box1">BOX111</div>
<div id="box2">BOX222</div> #box1, #box2 {
width: 100px;
height: 100px;
background: blue;
color: #fff;
position: relative;
}
#box1 { top: 500px; }
#box2 { top: 800px; } const intersectionObserver = new IntersectionObserver(function (entries) {
console.log('info:');
entries.forEach(item => {
console.log(item.target, item.intersectionRatio);
});
}, { threshold: [0.5, 1] });
intersectionObserver.observe(document.querySelector('#box1'));
intersectionObserver.observe(document.querySelector('#box2'));This technique is useful for data collection, lazy‑loading images, and any scenario where knowing when an element becomes visible is required.
MutationObserver
MutationObserver detects changes to an element's attributes and its child node list. The article creates a box with a button, then modifies its style, adds a child button, and removes a button after timed intervals, logging each mutation.
<div id="box"><button>光</button></div> #box {
width: 100px;
height: 100px;
background: blue;
position: relative;
} setTimeout(() => { box.style.background = 'red'; }, 2000);
setTimeout(() => {
const dom = document.createElement('button');
dom.textContent = '东东东';
box.appendChild(dom);
}, 3000);
setTimeout(() => { document.querySelectorAll('button')[0].remove(); }, 5000); const mutationObserver = new MutationObserver(mutationsList => {
console.log(mutationsList);
});
mutationObserver.observe(box, { attributes: true, childList: true });Such monitoring can be used to enforce persistent watermarks or react to dynamic DOM changes.
ResizeObserver
ResizeObserver watches size changes of an element. The article sets up a single box, changes its width after a delay, and logs the new dimensions.
<div id="box"></div> #box {
width: 100px;
height: 100px;
background: blue;
} const box = document.querySelector('#box');
setTimeout(() => { box.style.width = '200px'; }, 3000);
const resizeObserver = new ResizeObserver(entries => {
console.log('当前大小', entries);
});
resizeObserver.observe(box);This enables responsive UI adjustments and tracking of element resizing.
PerformanceObserver
PerformanceObserver listens to performance entries such as marks, measures, and resource timings, allowing developers to report timing data. The article shows marking a point, measuring a button click, and observing resource loads.
performance.mark('registered-observer'); performance.measure('button clicked', 'from', 'to'); const performanceObserver = new PerformanceObserver(list => {
list.getEntries().forEach(entry => {
console.log(entry); // upload
});
});
performanceObserver.observe({ entryTypes: ['resource', 'mark', 'measure'] });Collected data can be sent to analytics for performance analysis.
ReportingObserver
ReportingObserver captures browser reports about deprecated APIs and interventions (e.g., iframe removal, image placeholders). The article creates an observer that logs and uploads these reports.
const reportingObserver = new ReportingObserver((reports, observer) => {
for (const report of reports) {
console.log(report.body); // upload
}
}, { types: ['intervention', 'deprecation'] });
reportingObserver.observe();This provides visibility into browser‑initiated actions that are not exposed as errors.
Overall, the five Observer APIs—IntersectionObserver, MutationObserver, ResizeObserver, PerformanceObserver, and ReportingObserver—offer powerful tools for monitoring non‑user‑driven events in web applications.
IT Services Circle
Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.