乐闻世界logo
搜索文章和话题

What is Service Worker? What are its lifecycle and main functions?

2月18日 21:52

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

  1. Registration
javascript
if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js') .then(registration => console.log('SW registered')) .catch(error => console.log('SW registration failed')); }
  1. Installing
  • Triggers install event
  • Pre-caches static resources
  • Calling self.skipWaiting() can skip the waiting phase
  1. Activating
  • Triggers activate event
  • Cleans up old caches
  • Calling self.clients.claim() immediately controls all pages
  1. Activated
  • Starts intercepting network requests
  • Handles fetch events

Core Functions of Service Worker

1. Network Request Interception

javascript
self.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

  1. HTTPS Requirement: Must run in HTTPS environment (localhost excepted)
  2. Scope Limitation: Can only control registration path and its sub-paths
  3. Storage Limitation: Browsers limit cache size
  4. Lifecycle Management: Requires manual updates and cleanup
  5. Debugging Difficulty: Runs in independent thread, debugging is relatively complex

Best Practices

  1. Version Control: Add version numbers to caches for easier updates
  2. Cache Cleanup: Clean up old caches in activate event
  3. Error Handling: Properly handle network request failures
  4. Performance Optimization: Reasonably set cache expiration times
  5. Progressive Enhancement: Gracefully degrade in browsers that don't support Service Worker
标签:PWA