Service Worker is one of the core technologies of PWA. It is an independent thread running in the browser background with main functions including:
Service Worker Lifecycle
- Registration
javascriptif ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js') .then(registration => console.log('SW registered')) .catch(error => console.log('SW registration failed')); }
- Installing
- Triggers
installevent - Pre-caches static resources
- Calling
self.skipWaiting()can skip the waiting phase
- Activating
- Triggers
activateevent - Cleans up old caches
- Calling
self.clients.claim()immediately controls all pages
- Activated
- Starts intercepting network requests
- Handles
fetchevents
Core Functions of Service Worker
1. Network Request Interception
javascriptself.addEventListener('fetch', event => { event.respondWith( caches.match(event.request) .then(response => response || fetch(event.request)) ); });
2. Resource Caching Strategies
Cache First
- Prioritize reading from cache
- Request network only if cache doesn't exist
- Suitable for static resources
Network First
- Prioritize network requests
- Use cache if network fails
- Suitable for dynamic content
Stale While Revalidate
- Immediately return cache
- Simultaneously request network to update cache
- Balance speed and freshness
Network Only
- Don't use cache
- Suitable for real-time data
Cache Only
- Only read from cache
- Suitable for offline scenarios
3. Offline Support
- Cache critical resources
- Provide offline pages
- Return cached content when offline
4. Push Notifications
- Receive server pushes
- Display notifications
- Handle notification clicks
Service Worker Limitations
- HTTPS Requirement: Must run in HTTPS environment (localhost excepted)
- Scope Limitation: Can only control registration path and its sub-paths
- Storage Limitation: Browsers limit cache size
- Lifecycle Management: Requires manual updates and cleanup
- Debugging Difficulty: Runs in independent thread, debugging is relatively complex
Best Practices
- Version Control: Add version numbers to caches for easier updates
- Cache Cleanup: Clean up old caches in
activateevent - Error Handling: Properly handle network request failures
- Performance Optimization: Reasonably set cache expiration times
- Progressive Enhancement: Gracefully degrade in browsers that don't support Service Worker