Lesson 91 – Introduction to Service Workers
What are Service Workers?
A Service Worker is a script that runs in the background, separate from your web page.
It acts as a middleman between the browser and the network, allowing you to:
- Intercept network requests
- Manage caching for offline experiences
- Deliver push notifications
- Handle background sync
Key Characteristics:
- Runs independently from the web page.
- Doesn’t have direct access to the DOM.
- Works with HTTPS only (except on localhost during development).
How Service Workers Work
- Registration: Your web app tells the browser there’s a service worker.
- Installation: Browser installs the service worker.
- Activation: Browser activates the new worker and removes old ones.
- Fetching: Service worker can intercept requests and serve cached responses.
Basic Example
// Registering a Service Worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js')
.then(registration => {
console.log('Service Worker registered with scope:', registration.scope);
})
.catch(error => {
console.log('Service Worker registration failed:', error);
});
}
Basic service-worker.js
Example
// Install event
self.addEventListener('install', (event) => {
console.log('Service Worker installing.');
});
// Activate event
self.addEventListener('activate', (event) => {
console.log('Service Worker activated.');
});
// Fetch event
self.addEventListener('fetch', (event) => {
console.log('Fetch intercepted for:', event.request.url);
});
Why Service Workers Matter
- Offline Availability: Enable your site to work without a network.
- Performance Boost: Serve cached files faster than network files.
- Push Notifications: Send updates even when the app isn’t open.
- Background Sync: Sync data when connectivity is restored.
Key Events in a Service Worker:
Event | Purpose |
---|---|
install | Cache assets needed for offline use |
activate | Clean up old caches, take control |
fetch | Intercept network requests |
sync | Sync data when connectivity returns |
push | Handle push notifications |
In Summary
- Service Workers are powerful background scripts.
- You must register them in your main JavaScript file.
- They can intercept and handle network requests.
- They're crucial for building Progressive Web Apps (PWAs).