Intermediate 24 min readModule: Module 15: Progressive Web Apps (PWA) & Service Worker Cache
Progressive Web Apps, Service Workers & Offline Caching
Transform HTML websites into installable offline-capable Progressive Web Apps using manifest.json, Service Worker lifecycle events, and CacheStorage caching patterns.
What You Will Learn in This Lesson
- The anatomy of a Progressive Web App (PWA): manifest.json, HTTPS, and Service Workers
- Service Worker lifecycles: `install`, `activate`, and `fetch` event interception
- Caching strategies: Cache-First (Static Assets), Network-First (API Data), and Stale-While-Revalidate
- Registering background sync with `SyncManager` for guaranteed offline form submission
Introduction & Core Concept
Progressive Web Apps (PWAs) leverage modern browser APIs to deliver native app-like experiences directly through HTML. A Service Worker acts as a client-side programmable proxy server sitting between your web application and the network, enabling instant offline loading, background sync, and push notifications.
WHY DOES THIS MATTER IN THE REAL WORLD?
Users on flaky mobile connections frequently experience offline disconnections. PWAs with robust Service Worker caching load instantly from cache, providing a seamless offline experience and boosting user retention.
Syntax & Structure
html
navigator.serviceWorker.register('/sw.js');self.addEventListener('fetch', (event) => { event.respondWith(caches.match(event.request));});Registering a Service Worker and Stale-While-Revalidate Caching
htmlhtml
123456789101112131415161718192021222324252627282930313233343536<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><link rel="manifest" href="/manifest.json"><meta name="theme-color" content="#3b82f6"><title>KWAS Academy PWA</title></head><body><h1>KWAS Academy Offline-First Platform</h1><p id="network-status">Network Status: Online</p><script>// 1. Register Service Worker on window loadif ('serviceWorker' in navigator) {window.addEventListener('load', async () => {try {const registration = await navigator.serviceWorker.register('/sw.js');console.log("Service Worker registered with scope:", registration.scope);} catch (err) {console.error("Service Worker registration failed:", err);}});}// 2. Monitor network connection statewindow.addEventListener('online', () => {document.getElementById('network-status').textContent = "Network Status: Online (Connected)";});window.addEventListener('offline', () => {document.getElementById('network-status').textContent = "Network Status: Offline (Serving cached docs)";});</script></body></html>
Line-by-Line Technical Breakdown
1Cache Strategies: Cache-First serves immediately from CacheStorage and falls back to network (best for fonts, icons, images). Network-First queries network first and falls back to cache (best for live market data). Stale-While-Revalidate serves cached content immediately while silently updating the cache in the background.
Try It Yourself (Interactive Editor)
Modify the code in real-time and click Run to test live browser output and console logs.
Intelligent Code Runner & Live Sandbox[HTML]
HTML SOURCE EDITOR
Interactive Live CodeCommon Mistakes & How to Avoid Them
#1: Caching API mutation requests (POST/PUT/DELETE) inside CacheStorage.
CacheStorage only supports caching idempotent GET requests. POST requests should be queued in IndexedDB via Background Sync.
Incorrect / Antipattern
if (event.request.method === 'POST') { caches.put(event.request, response); }Correct / Professional Solution
if (event.request.method === 'GET') { event.respondWith(caches.match(event.request)); }Industry Best Practices & Professional Standards
- Version cache names (`kwas-cache-v1`) to automatically delete obsolete assets during the `activate` event.
- Use Stale-While-Revalidate for documentation content to ensure instant rendering and fresh background updates.
- Always serve PWAs exclusively over secure HTTPS connections.
Lesson Summary & Core Takeaways
- PWAs make web applications installable and operable offline.
- Service Workers intercept network traffic and manage CacheStorage.
- Stale-While-Revalidate balances zero-latency rendering with background data freshness.