JavaScript - Observers & Performance APIs
Overview
Estimated time: 15–20 minutes
Observer APIs let you react to DOM changes and element visibility. Performance APIs help measure and optimize your code.
Learning Objectives
- Use MutationObserver and IntersectionObserver.
- Measure performance with the Performance API.
Prerequisites
MutationObserver Example
const observer = new MutationObserver(mutations => {
mutations.forEach(mutation => console.log(mutation));
});
observer.observe(document.body, { childList: true });
IntersectionObserver Example
const io = new IntersectionObserver(entries => {
entries.forEach(entry => console.log(entry.isIntersecting));
});
io.observe(document.getElementById('target'));
Performance API Example
performance.mark('start');
// ... code ...
performance.mark('end');
performance.measure('My Task', 'start', 'end');
Common Pitfalls
- Observers can introduce performance overhead if not used carefully.
Summary
Observer and performance APIs are essential for responsive, efficient web apps.