- Courses
- 💻Programming Languages
- 🌐JavaScript
- Tooling and Performance
- Web APIs
On this page
Web APIs: Storage and Observation
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
Modern web development relies on a suite of browser-native APIs that extend the capabilities of the JavaScript engine. To build absolute expert-level applications, you must move beyond simple DOM manipulation and master APIs that handle long-term data persistence and high-performance element observation. This lesson focuses on the Web Storage API and the Intersection Observer API.
The Web Storage API: Local vs. Session
The Web Storage API provides a mechanism for browsers to store key/value pairs in a much more intuitive fashion than cookies. It consists of two distinct mechanisms: LocalStorage and SessionStorage.
Comparison of Storage Types
FeatureLocalStorageSessionStorage****PersistencePermanent (remains after browser close)Temporary (cleared when tab/window closes)ScopeShared across all tabs of the same originLimited to the specific tab that created itCapacityApproximately 5MB to 10MBApproximately 5MBData FormatStrings onlyStrings only
Implementation and Serialization
Since these APIs only store strings, you must use JSON.stringify() when saving objects or arrays, and JSON.parse() when retrieving them.
// Saving to LocalStorage
const userSettings = { theme: "dark", fontSize: 16 };
localStorage.setItem("settings", JSON.stringify(userSettings));
// Retrieving from LocalStorage
const savedSettings = JSON.parse(localStorage.getItem("settings"));
// Removal
localStorage.removeItem("settings");
localStorage.clear(); // Deletes everything in storage for this origin
Intersection Observer API
In the past, detecting if an element was visible on the screen required attaching heavy event listeners to the scroll event and manually calculating offsets using getBoundingClientRect(). This was computationally expensive and often caused layout thrashing.
The Intersection Observer API provides a high-performance, asynchronous way to observe changes in the intersection of a target element with an ancestor element or the top-level document's viewport.
Core Mechanics
The observer is initialized with a callback function and an options object.
- Root: The element used as the viewport. Defaults to the browser viewport if null.
- RootMargin: Similar to CSS margins; it grows or shrinks the area used for intersection.
- Threshold: A number (or array of numbers) indicating what percentage of the target's visibility should trigger the callback (e.g.,
0.5means 50% visibility).
const options = {
root: null, // use the viewport
threshold: 0.1, // trigger when 10% of the element is visible
};
const observer = new IntersectionObserver((entries, observer) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
console.log("Element is visible!");
// Perform action: e.g., trigger animation or load image
observer.unobserve(entry.target); // Stop observing after first trigger
}
});
}, options);
observer.observe(document.querySelector(".target-element"));
Practical Industry Use Cases
Lazy Loading Images
By using Intersection Observer, you can delay the loading of high-resolution images until the user actually scrolls near them. This significantly reduces initial page load time and saves bandwidth.
Infinite Scroll
Instead of calculating scroll height, you can place a "sentinel" element at the bottom of your list. When the observer detects the sentinel, it triggers a fetch for the next page of data.
Scroll-Linked Animations
Trigger CSS classes or JavaScript animations only when a specific section of the page enters the viewport, ensuring that the user actually sees the visual effect.
Security and Performance Standards
- Storage Security: Never store sensitive data like passwords, credit card numbers, or personally identifiable information (PII) in LocalStorage. It is accessible via any script running on the page, making it vulnerable to Cross-Site Scripting (XSS) attacks.
- Storage Errors: Always wrap
localStorage.setItemin atry/catchblock. If the user is in "Private/Incognito" mode or their storage quota is full, the call will throw an exception. - Observer Lifecycle: Always call
observer.disconnect()if you are building single-page applications (SPAs) and the observed elements are removed from the DOM. This prevents memory leaks. - Prefer Observer over Scroll Listeners: For any "visibility-based" logic, the Intersection Observer is always the superior choice for performance as it runs on the browser's internal optimization layer rather than the main thread's event loop.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Performance Optimization
Next
Conclusions
-
The Web Storage API: Local vs. Session
- Comparison of Storage Types
- Implementation and Serialization
-
Intersection Observer API
- Core Mechanics
-
Practical Industry Use Cases
- Lazy Loading Images
- Infinite Scroll
- Scroll-Linked Animations
-
Security and Performance Standards
