Modern JavaScript APIs
45 minThe browser provides a vast array of Web APIs that extend JavaScript's capabilities far beyond simple DOM manipulation. Mastering these APIs allows you to build app-like experiences.
**Intersection Observer** efficiently detects when an element enters the viewport, enabling lazy loading of images and infinite scrolling without scroll event listeners.
**Resize Observer** allows you to respond to changes in an element's size, which is crucial for building responsive components that depend on their container's width, not just the window's.
**Mutation Observer** lets you watch for changes in the DOM tree itself (nodes added/removed, attributes changed), useful for building extensions or reacting to third-party script injections.
Key Concepts
- Intersection Observer (Visibility).
- Resize Observer (Element Dimensions).
- Mutation Observer (DOM Changes).
- Geolocation & Notification APIs.
- Web Storage (LocalStorage/IndexedDB).
Learning Objectives
Master
- Implementing lazy loading images
- Building infinite scroll features
- Creating container queries with ResizeObserver
- Persisting data with browser storage
Develop
- Performance optimization (removing scroll listeners)
- Progressive Web App (PWA) features
- Hardware access (Camera, GPS)
Tips
- Always disconnect your observers (`observer.disconnect()`) when the component unmounts to prevent memory leaks.
- Use `IntersectionObserver` with `rootMargin` to start loading images *before* they appear on screen.
- Check for API support (`if ('IntersectionObserver' in window)`) before using it.
- Use `requestAnimationFrame` for visual updates triggered by these APIs.
Common Pitfalls
- Using scroll event listeners for visibility checks (terrible performance).
- Observing too many elements individually (use a single observer for multiple targets).
- Blocking the main thread in observer callbacks (keep them lightweight).
- Storing sensitive data in LocalStorage (it's accessible by any script).
Summary
- Web APIs power modern apps.
- Observers replace expensive event listeners.
- They enable lazy loading and responsiveness.
- Always handle cleanup and support checks.
Exercise
Create an Intersection Observer to detect when an element becomes visible.
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
console.log('Element is visible!');
}
});
});
observer.observe(document.querySelector('.target'));
Exercise Tips
- Add options to the observer: { rootMargin: '50px', threshold: 0.5 }.
- Use observer.unobserve() to stop observing an element.
- Try using ResizeObserver to detect element size changes.
- Implement lazy loading by loading images when they become visible.