Web APIs: DOM, Events, and Storage
Web APIs: DOM, Events, and Storage
Browser host platform capabilities, DOM tree manipulation, and client-side persistence.
The Customer and the Supermarket Shelves
Web APIs are not defined by ECMAScript; they are host platform APIs exposed by browser engines (in C++) to allow JavaScript to interact with documents, user inputs, and device storage.
The DOM Tree and Traversal
The HTML document is parsed into a tree of Nodes. Use `querySelector`, `querySelectorAll`, `closest`, and `matches` for fast, declarative element lookups.
Layout Thrashing Prevention
Interleaving DOM reads (`offsetHeight`) and DOM writes (`style.height`) forces synchronous layout recalculation. Always batch reads first, then batch writes.
localStorage vs sessionStorage
`localStorage` persists across tabs and browser restarts (~5MB quota). `sessionStorage` is scoped to a single tab and cleared when the tab closes (~5MB quota).
Modern Observer APIs
`IntersectionObserver` efficiently checks when elements enter viewport (lazy loading). `ResizeObserver` detects element dimensions. `MutationObserver` watches DOM mutations.
Safe JSON LocalStorage wrapper and IntersectionObserver setup:
// Robust LocalStorage Wrapper with JSON Serialization
const storage = {
get(key, fallback = null) {
try {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : fallback;
} catch {
return fallback;
}
},
set(key, value) {
try {
localStorage.setItem(key, JSON.stringify(value));
return true;
} catch (err) {
console.error("Storage quota exceeded or disabled:", err);
return false;
}
}
};
// Simulating browser storage usage
storage.set("theme_preference", { dark: true, accent: "emerald" });
console.log("Retrieved theme:", storage.get("theme_preference"));
Retrieved theme: { dark: true, accent: 'emerald' }
Storing Sensitive Tokens in localStorage
The Risk: Storing JWTs or passwords in `localStorage` makes them accessible to any JavaScript script on the page, vulnerable to Cross-Site Scripting (XSS) attacks.
The Fix: Store sensitive authentication tokens in `HttpOnly`, `Secure`, `SameSite` cookies.
Synchronous Storage Blocking Main Thread
The Risk: Reading or writing huge JSON objects to `localStorage` blocks the main thread because Web Storage APIs are synchronous.
The Fix: Use `IndexedDB` (via libraries like `idb`) for large datasets or offline data caching.
- ✓ Web APIs are provided by the browser, not ECMAScript core.
- ✓ `localStorage` persists indefinitely; `sessionStorage` is tab-scoped.
- ✓ Both storage APIs are synchronous, string-only, and capped at ~5MB.
- ✓ Avoid Layout Thrashing: Batch DOM style reads before DOM writes.
- ✓ Use `IntersectionObserver` for high-performance image lazy loading and infinite scroll.