How to register and activate Service Worker
How to register and activate 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: