093
LVL 04 — SENIOR-IN-TRAININGSESSION 093DAY 93

OFFLINE & PWA

🎫 PIXELCRAFT-079
Feature | 🔴 Expert | Priority: 🟡 Medium

PixelCraft should work without internet. Static assets cached. Edits saved locally and synced when back online. Add Service Worker, offline indicators, and background sync. Make it a real PWA — installable, offline-capable, fast.
CONCEPTS.UNLOCKED
⚙️
Service Workers
Scripts that intercept network requests. A programmable proxy between your app and the network. Cache assets, serve them offline, handle background sync. Runs even when the app is closed.
📦
Cache Strategies
Cache-first: fast, may be stale. Network-first: fresh, may be slow. Stale-while-revalidate: serve cache immediately, update in background. Choose per resource type.
📡
Offline Detection
navigator.onLine + online/offline events. Detect when the user goes offline. Show a banner. Queue changes locally. Sync when connection returns.
🔄
Background Sync
Queue changes offline → send when reconnected. User edits an image while offline. Changes are stored in IndexedDB. When the connection returns, the queue is processed automatically.
📱
PWA Basics
Manifest + Service Worker = installable app. Add to Home Screen on mobile. Full-screen experience. Offline support. Push notifications. A website that behaves like a native app.
HANDS-ON.TASKS
01
Register a Service Worker
// In main app: if ('serviceWorker' in navigator) { navigator.serviceWorker .register('/sw.js') .then(reg => console.log( 'SW registered:', reg.scope)) .catch(err => console.error( 'SW registration failed:', err)); }
02
Cache-First for Static Assets
// sw.js const CACHE_NAME = 'pixelcraft-v1'; const STATIC_ASSETS = [ '/', '/index.html', '/assets/main.js', '/assets/main.css', '/manifest.json', ]; // Install: pre-cache static assets self.addEventListener('install', (event) => { event.waitUntil( caches.open(CACHE_NAME) .then(cache => cache.addAll(STATIC_ASSETS)) ); }); // Fetch: strategy per resource type self.addEventListener('fetch', (event) => { // Static assets → cache-first if (event.request.url.match( /\.(js|css|png|jpg|woff2?)$/)) { event.respondWith( caches.match(event.request) .then(cached => cached || fetch(event.request)) ); return; } // API requests → network-first if (event.request.url .includes('/api/')) { event.respondWith( fetch(event.request) .then(response => { const clone = response.clone(); caches.open(CACHE_NAME) .then(cache => cache.put( event.request, clone)); return response; }) .catch(() => caches.match(event.request)) ); return; } });
Static assets rarely change → cache-first is perfect (fast, use cache, skip network). API data changes often → network-first (try network, fall back to cache if offline).
03
Offline Indicator
function useOnlineStatus(): boolean { const [isOnline, setIsOnline] = useState(navigator.onLine); useEffect(() => { const goOnline = () => setIsOnline(true); const goOffline = () => setIsOnline(false); window.addEventListener( 'online', goOnline); window.addEventListener( 'offline', goOffline); return () => { window.removeEventListener( 'online', goOnline); window.removeEventListener( 'offline', goOffline); }; }, []); return isOnline; } function OfflineBanner() { const isOnline = useOnlineStatus(); if (isOnline) return null; return ( <div className="bg-amber-600 text-white text-center py-1 text-sm"> You're offline. Changes will sync when you reconnect. </div> ); }
04
Queue Offline Edits & Sync
// Store pending changes in IndexedDB async function queueOfflineAction( action: OfflineAction ) { const db = await openDB( 'pixelcraft-offline', 1); await db.add('pending-actions', { ...action, timestamp: Date.now(), }); } // Sync when back online window.addEventListener('online', async () => { const db = await openDB( 'pixelcraft-offline', 1); const actions = await db.getAll( 'pending-actions'); for (const action of actions) { try { await api( action.url, action.options); await db.delete( 'pending-actions', action.id); } catch (err) { console.error( 'Sync failed:', action, err); } } });
05
Web App Manifest
// manifest.json { "name": "PixelCraft", "short_name": "PixelCraft", "start_url": "/", "display": "standalone", "background_color": "#0a0a0f", "theme_color": "#e94560", "icons": [ { "src": "/icons/icon-192.png", "sizes": "192x192", "type": "image/png" }, { "src": "/icons/icon-512.png", "sizes": "512x512", "type": "image/png" } ] } // index.html: // <link rel="manifest" // href="/manifest.json">
06
Close the Ticket
git switch -c feature/PIXELCRAFT-079-offline-pwa git add public/ src/ git commit -m "Add Service Worker + offline sync + PWA manifest (PIXELCRAFT-079)" git push origin feature/PIXELCRAFT-079-offline-pwa # PR → Review → Merge → Close ticket ✅
CS.DEEP-DIVE

Cache hierarchies operate at every level of computing.

The Service Worker is a programmable cache — you control the strategy per resource type. The same pattern exists at every layer.

// Cache layers (small → large):

CPU
  L1 → L2 → L3 → RAM → Disk
  Each layer: bigger, slower

Web
  Service Worker cache
  → Browser HTTP cache
  → CDN edge cache
  → Origin server
  → Database

// Each layer has a strategy:
CPU    → LRU replacement
Redis  → TTL + eviction policies
CDN    → Cache-Control headers
SW     → cache-first / network-first

// Understanding caching at one level
// teaches you caching at every level.
"PWA Lab"
[A]Add stale-while-revalidate for the gallery API: serve cached thumbnails instantly, then fetch fresh data in the background. If anything changed, update the UI seamlessly. Best of both worlds — fast AND fresh.
[B]Add cache versioning: when you deploy a new version, update CACHE_NAME to 'pixelcraft-v2'. In the activate event, delete old caches. Users always get the latest code after the next visit.
[C]Research: what is Workbox (by Google)? It abstracts Service Worker caching strategies into a declarative config. Compare hand-written SW code to Workbox. When is the abstraction worth it?
REF.MATERIAL
ARTICLE
MDN Web Docs
Official Service Worker reference: lifecycle (install, activate, fetch), cache API, and background sync. The complete guide.
SWOFFICIALESSENTIAL
VIDEO
Traversy Media
Practical Service Worker tutorial: registration, caching strategies, offline fallback, and cache versioning. Hands-on implementation.
SWTUTORIAL
ARTICLE
Jake Archibald (Google)
Every caching strategy explained with code: cache-first, network-first, stale-while-revalidate, cache then network. The definitive caching strategy reference.
CACHINGSTRATEGIESESSENTIAL
ARTICLE
Google Chrome
Libraries for Service Worker caching: precaching, runtime caching, strategies, and routing. The production-ready way to build offline-capable apps.
WORKBOXOFFICIAL
VIDEO
Fireship
Quick PWA overview: manifest, Service Worker, installability, and offline support. What makes a website a Progressive Web App.
PWAQUICK
// LEAVE EXCITED BECAUSE
Disconnect WiFi. PixelCraft still works. Edit an image. Reconnect. Changes sync automatically. It's a real PWA — installable, offline-capable, fast. Your web app now behaves like a native app.