Service workers API example
Service Workers are a key feature of Progressive Web Apps (PWAs). They act as a proxy between the web browser and the network, allowing developers to intercept network requests, cache resources, and provide offline experiences.
How Service Workers Work
-
Registration:
- A service worker is registered with the browser. This is typically done from the main JavaScript file of your web application.
-
Installation:
- Once registered, the browser attempts to install the service worker. During this phase, you can cache assets for offline use.
-
Activation:
- After installation, the service worker moves to the activation phase. This is where you can clean up old caches and perform any necessary updates.
-
Interception:
- The service worker can intercept network requests made by your web application and decide how to handle them (e.g., serve from cache, fetch from network).
Example: Registering and Installing a Service Worker
1. Registering the Service Worker
In your main JavaScript file (e.g., main.js
):
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/service-worker.js')
.then(registration => {
console.log('Service Worker registered with scope:', registration.scope);
})
.catch(error => {
console.error('Service Worker registration failed:', error);
});
});
}
2. Creating the Service Worker
Create a file named service-worker.js
:
const CACHE_NAME = 'my-cache-v1';
const urlsToCache = [
'/',
'/styles/main.css',
'/scripts/main.js',
'/images/logo.png'
];
// Installation: Cache resources
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => {
console.log('Opened cache');
return cache.addAll(urlsToCache);
})
);
});
// Activation: Clean up old caches
self.addEventListener('activate', event => {
const cacheWhitelist = [CACHE_NAME];
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
if (!cacheWhitelist.includes(cacheName)) {
return caches.delete(cacheName);
}
})
);
})
);
});
// Fetch: Serve cached content if available, else fetch from network
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.then(response => {
// Cache hit - return response
if (response) {
return response;
}
return fetch(event.request);
})
);
});
Explanation:
Registration
- The service worker is registered when the page loads. If successful, the service worker's scope is logged to the console.
Installation
- During the installation phase, resources defined in the
urlsToCache
array are cached. Theevent.waitUntil
method ensures the installation process completes before the service worker is considered installed.
Activation
- During the activation phase, old caches are cleaned up to ensure that only the current cache (
CACHE_NAME
) is used. This prevents outdated resources from being served.
Fetch Interception
- The service worker intercepts all network requests made by the web application. It first checks the cache for a matching request. If a match is found, it returns the cached response. If no match is found, it fetches the resource from the network.
Published on: Jul 25, 2024, 02:28 AM