PWA Features
- Offline Access - Study even without internet connection
- Install to Home Screen - Launch like a native app on mobile
- Fast Loading - Cached assets load instantly
- Background Sync - Sync study data when connection returns
Service Worker Lifecycle
The service worker operates through three main lifecycle events:1. Install Event
Triggered when the service worker is first registered or when a new version is detected.- Creates a new cache with the current version name
- Pre-caches all critical assets (app shell)
- Waits for caching to complete before installing
2. Activate Event
Triggered after installation when the service worker takes control.- Retrieves all existing cache names
- Deletes old caches that don’t match the current version
- Ensures only the latest assets are stored
Why delete old caches during activation?
Why delete old caches during activation?
Each service worker version creates a new cache (
estudo-organizado-v1, estudo-organizado-v2, etc.). Without cleanup:- Multiple cache versions accumulate
- Storage quota gets exhausted
- Stale assets might be served
- The new service worker has already installed
- Old caches are no longer needed
- The app is transitioning to the new version
3. Fetch Event
Triggered on every network request from the app.- Filters requests (only intercepts GET requests to same-origin)
- Checks cache first
- Falls back to network if not cached
- Dynamically caches successful network responses
- Provides offline fallback for HTML pages
Caching Strategy
The service worker implements a Cache First with Network Fallback strategy:Strategy Breakdown
1. Cache First
- Instant loading for cached assets
- Works offline
- Reduces bandwidth usage
- May serve stale content until service worker updates
- Not suitable for real-time data (API calls excluded)
2. Dynamic Caching
- User-uploaded images
- Lazily loaded modules
- Dynamically imported dependencies
Response Cloning:
fetchRes.clone() is critical because Response streams can only be read once. We need two copies - one for caching, one to return to the app.3. Offline Fallback
- Single-page app routing to still work
- User sees the app shell instead of browser error page
- Client-side router can handle the route
App Shell Architecture
TheASSETS array defines the app shell - critical resources pre-cached during installation:
What’s Included
- HTML Shell - Base page structure
- Core Styles - UI rendering CSS
- JavaScript Modules - All app logic
- Icons - Favicon and app icons
What’s Excluded
- User Data - Stored in IndexedDB, not service worker cache
- External APIs - Google Drive, Cloudflare sync endpoints
- POST Requests - Dynamic operations that shouldn’t be cached
Request Filtering
The service worker selectively intercepts requests:1. Method Filtering
2. Origin Filtering
- External APIs (Google Drive, Cloudflare) have their own caching headers
- Third-party CDNs shouldn’t be cached (may update independently)
- Only app-owned resources should go through the cache strategy
Why check pathname.startsWith('/src/')?
Why check pathname.startsWith('/src/')?
This allows caching of development assets during local testing:In production, all same-origin requests are cached regardless of path.
Cache Versioning
Version Update Flow
- Developer updates code → Increments version to
v2 - User visits app → Browser detects new service worker
- Install event → Creates
estudo-organizado-v2cache - Activate event → Deletes
estudo-organizado-v1 - New version active → App now serves from v2 cache
Atomic Updates: The old cache remains active until the new one fully installs. Users never experience a broken state during updates.
Offline Behavior
Scenario 1: First Visit (Online)
- Service worker installs
- App shell cached
- User interacts with app
- Dynamic assets cached as encountered
Scenario 2: Return Visit (Offline)
- Service worker intercepts all requests
- Returns cached app shell instantly
- App loads from cache (less than 100ms)
- User can study with cached data
- Sync operations queued for when online
Scenario 3: Partial Cache (Offline)
- Fetch fails (offline)
- Fallback to
index.html - Client-side router renders the route
- Works because app is a SPA
Installation & Registration
The service worker is registered from the main app:Browser Support
Supported: Chrome, Edge, Firefox, Safari 11.1+, OperaNot Supported: IE11, older Safari versionsThe app gracefully degrades - service worker features are optional enhancements.
Cache Size Management
Browsers limit cache storage (typically 50-250MB depending on device).Current Strategy
- App shell: ~500KB
- Dynamic assets: Unbounded (browser manages eviction)
- User data: Stored in IndexedDB (separate quota)
Future Optimization
Debugging Service Workers
Chrome DevTools
- Open DevTools → Application tab
- Select Service Workers panel
- View status, update, unregister
Common Issues
Service worker not updating
Service worker not updating
Cause: Browser caches the service worker file itself.Solution:Or in DevTools: Check “Update on reload”
Cache not clearing
Cache not clearing
Cause: Old cache version wasn’t deleted.Solution:
Offline fallback not working
Offline fallback not working
Cause:
index.html not in cache or path mismatch.Solution: Ensure './index.html' matches the actual cache entry:Performance Metrics
Load Time Comparison
| Scenario | First Load | Cached Load | Offline Load |
|---|---|---|---|
| Without SW | 2.5s | 2.5s | ❌ Fails |
| With SW | 2.5s | 0.3s | 0.3s |
Cache Hit Rate
Typical cache hit rates:- App shell: 100% (pre-cached)
- Dynamic assets: 60-80% (depends on user navigation)
- API calls: 0% (intentionally not cached)
Security Considerations
Same-Origin Policy
- Cache poisoning from external sources
- Cross-site scripting via cached responses
- Unauthorized data access
Content Security Policy
Service worker respects CSP headers - cached responses maintain their original security policies.Future Enhancements
Potential Features:
- Background sync for study session data
- Push notifications for study reminders
- Periodic background sync for updated exam content
- Advanced cache strategies (network-first for API data)
Related Documentation
- State Management - How user data is stored separately in IndexedDB
- Cloudflare Sync - How online sync works alongside offline caching
- Google Drive Sync - Alternative cloud backup integration