How to Register and Activate a Service Worker
Using a Service Worker begins with its registration, typically in your main JavaScript file. It can only be registered in an HTTPS environment (except for localhost) because it can control network requests.
Example of Service Worker Registration:
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js')
.then(registration => {
console.log('Service Worker registered:', registration);
})
.catch(error => {
console.log('Service Worker registration failed:', error);
});
});
}
In the sw.js file, we can write the following:
// sw.js
self.addEventListener('install', event => {
console.log('Service Worker installing...');
// Here, we can pre-cache files
});
self.addEventListener('activate', event => {
console.log('Service Worker activating...');
// Here, we can clean up old caches
});
self.addEventListener('fetch', event => {
console.log('Fetch request received:', event.request.url);
// Here, we can modify the request, serve from cache or network
});
A Service Worker has three main phases: install, activate, and fetch:
- install – During the installation phase, resources can be pre-cached.
- activate – During activation, old caches can be cleaned up, and new services can be prepared.
- fetch – Every time the site makes a network request, the Service Worker can intercept it and respond from the cache or network.