Chapter 1 of ?
html 8 min read

HTML Mastery — Chapter 18: Web Storage & Web Workers

1. Web Storage API: localStorage vs sessionStorage

The HTML5 Web Storage API provides key-value pair storage directly within the user’s browser. It replaces legacy HTTP cookies for client-side data persistence by offering higher storage capacity (~5MB per origin) without transmitting data on every server request.

Feature localStorage sessionStorage
Lifespan Persists indefinitely until explicitly deleted via code or cleared by user. Expires automatically as soon as the tab or window session closes.
Scope Shared across all windows/tabs with the same Origin (protocol://domain:port). Restricted strictly to the current browser tab and session.
Storage Capacity ~5 MB per origin (varies by browser). ~5 MB per tab session.

Core Web Storage Methods

storage-demo.js
// 1. Store String Data localStorage.setItem('username', 'AlexDev'); sessionStorage.setItem('sessionToken', 'XYZ-9876'); // 2. Store JSON Objects (Must stringify objects) const userProfile = { id: 101, theme: 'dark', roles: ['admin', 'dev'] }; localStorage.setItem('userProfile', JSON.stringify(userProfile)); // 3. Retrieve & Parse Data const storedName = localStorage.getItem('username'); const parsedProfile = JSON.parse(localStorage.getItem('userProfile')); // 4. Remove Specific Item or Clear All localStorage.removeItem('username'); localStorage.clear(); // Danger: Removes all keys for origin
Try It Yourself »
Try It Yourself — Web Storage Persistence Simulator

Test saving values to localStorage vs sessionStorage live:

localStorage['demo_val']:--
sessionStorage['demo_val']:--

2. Storage Scope & Cross-Tab window.onstorage Event

When localStorage is modified in one browser tab, other open tabs sharing the exact same origin receive a native storage event.

Web Storage Scope & Cross-Tab Synchronization Architecture
Browser Tab 1 (Origin A) localStorage.setItem('theme','dark') Triggers Storage Event ➔ Shared Origin Storage Key-Value Persistence Engine Browser Tab 2 (Origin A) window.onstorage Listener event.key, event.newValue Storage Quotas (~5 MB Limit per Origin) Exceeding quota throws DOMException: QuotaExceededError

Listening for Cross-Tab Storage Changes

window.addEventListener('storage', (event) => { console.log(`Modified Key: ${event.key}`); console.log(`Old Value: ${event.oldValue}`); console.log(`New Value: ${event.newValue}`); console.log(`Triggering URL: ${event.url}`); });
Try It Yourself »
Try It Yourself — Cross-Tab Storage Event Listener

Click to simulate a storage update and watch the event listener inspect details:


3. Multithreading with Web Workers (new Worker())

JavaScript normally runs on a single main thread. Heavy computations (complex math, image processing, large datasets) can freeze the UI and create lag. Web Workers allow scripts to run in background threads without blocking the DOM thread.

Worker Restrictions: Web Workers run in a separate global context (DedicatedWorkerGlobalScope). They cannot access the DOM (no document, window, or parent access). However, they can use fetch, IndexedDB, WebSockets, and timers.

Instantiating a Web Worker

// 1. Dedicated Worker File (worker.js) const worker = new Worker('worker.js'); // 2. Inline Blob Worker (Useful for self-contained scripts) const workerCode = ` self.onmessage = function(e) { console.log("Worker received data:", e.data); self.postMessage("Processing Complete!"); }; `; const blob = new Blob([workerCode], { type: 'application/javascript' }); const inlineWorker = new Worker(URL.createObjectURL(blob));
Try It Yourself »
Try It Yourself — Inline Web Worker Initializer

Click to spawn a live Web Worker thread and pass data across worker threads:


4. Worker Architecture & Message Passing

The Main Thread and Web Worker communicate asynchronously via postMessage() and the onmessage event handler.

Main Thread vs Web Worker Thread Architecture
MAIN THREAD (UI & DOM) DOM Rendering & User Clicks worker.postMessage(heavyTask) postMessage() postMessage(result) WEB WORKER THREAD self.onmessage Listener Heavy Computation (Loop)

Main Thread vs Worker Thread Communication Pattern

// Main Thread Script const worker = new Worker('compute.js'); // Send data to worker worker.postMessage({ number: 5000000 }); // Listen for result worker.onmessage = function(e) { console.log(`Calculation Result: ${e.data.result}`); worker.terminate(); // Terminate worker thread when done }; // Handle Worker Errors worker.onerror = function(error) { console.error(`Worker error: ${error.message} at line ${error.lineno}`); };
Try It Yourself »
Try It Yourself — Main Thread vs Worker Thread Comparison

Test UI responsiveness while performing heavy loops on Main Thread vs Background Worker:

UI Animation State (Watch if ring freezes!)

5. Interactive Project: Multithreaded Prime Calculator & Storage Cache

Build a high-performance Multithreaded Prime Number Calculator that offloads heavy mathematical computation to a Web Worker background thread and caches calculated results in localStorage.

Background Computation + Storage Caching Architecture

// Check localStorage cache first const cacheKey = `primes_${limit}`; if (localStorage.getItem(cacheKey)) { console.log("Returned from localStorage cache instantly!"); return JSON.parse(localStorage.getItem(cacheKey)); } // Otherwise offload to Web Worker thread const worker = new Worker('prime-worker.js'); worker.postMessage(limit); worker.onmessage = (e) => { localStorage.setItem(cacheKey, JSON.stringify(e.data)); console.log("Calculation finished & cached!"); };
Try It Yourself »
Try It Yourself — Multithreaded Prime Calculator & Storage Cache

Compute prime numbers up to N in background thread with local cache:


Hands-On Challenge: Build an Offline Text Editor with Auto-Save Worker

Build an auto-saving note taking app that stores document drafts in localStorage every 3 seconds and offloads word count & character count statistics calculation to a Web Worker.

Launch Code Playground & Try »

Chapter 18 Key Takeaways

  • Use localStorage for persistent client storage; use sessionStorage for single-session tab data.
  • Always stringify JavaScript objects with JSON.stringify() before storing.
  • Listen for cross-tab changes using window.addEventListener('storage', callback).
  • Web Workers allow running background threads (`new Worker()`) without blocking UI animation or DOM events.
  • Web Workers cannot access DOM elements or global window context directly.
Done with this chapter?
Mark it complete to track your progress and unlock your certificate.
Next Up

Learner Reviews

Write a Review
Share your experience to help other learners.
Your Rating *