I have a PWA with multiple different languages and would like to cache only language specific files on install. I can’t find out a way to communicate the language to the service worker during install. Ideas on how I could do it?
My js code to initiate the service worker:
JavaScript
x
7
1
navigator.serviceWorker.register('../service-worker.js', { scope: '/' }).then((reg) => {
2
console.log('Service worker registered successfully.', reg);
3
registration = reg;
4
}).catch(function (e) {
5
console.error('Error during service worker registration:', e);
6
});
7
My code in the service-worker.js:
JavaScript
1
13
13
1
self.addEventListener('install', function(event) {
2
messageAllClients('Event-Install');
3
// Perform install steps
4
event.waitUntil(
5
caches.open(CACHE_NAME).then(function(cache) {
6
messageAllClients('Language detected by the service worker: '+language);
7
messageAllClients('Pre-caching offline page');
8
return cache.addAll(FILES_TO_CACHE);
9
})
10
);
11
self.skipWaiting();
12
});
13
Advertisement
Answer
Variables can be relayed to the service worker during install via GET attributes, as @JeffPosnick pointed out in the comment.