2. Offline Support: Registering Service Worker
The Service Worker is a JavaScript file that acts as a proxy server between the browser and the network. It is the core technology that enables offline usage and fast loading times.
2.1. Service Worker Registration (main.js)
Write the code to register the Service Worker when the web app loads. Note that it only works in a secure (HTTPS) context.
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/service-worker.js').then(function(registration) {
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}, function(err) {
console.log('ServiceWorker registration failed: ', err);
});
});
}
2.2. Service Worker Initialization (service-worker.js)
The service-worker.js file is where you define caching strategies and set up event listeners. Initially, include only the basic setup.
const CACHE_NAME = 'pwa-guide-cache-v1';
// Event triggered when the Service Worker is installed
self.addEventListener('install', (event) => {
console.log('[Service Worker] Installed');
});
// Event triggered when the Service Worker is activated
self.addEventListener('activate', (event) => {
console.log('[Service Worker] Activated');
});