Please note that this is just my 2 cents to the service worker topic. It could be outdated, deprecated or overly complicated.
Files:
- The actual service worker (serviceworker.js)
- your existing JS on your page (e.g. main.js)
In main.js, the service worker gets installed like this:
const serviceWorkerUri = '/serviceworker-v1.9.js';
function initSubscriptions() {
if ('serviceWorker' in navigator === false) {
return Promise.reject('Service worker not supported');
}
// activate button
return navigator.serviceWorker
.register(serviceWorkerUri)
.then(function() {
console.log('service worker registered');
});
}
You need to make sure, that the serviceworker file (e.g. /serviceworker-v1.9.js
) is located in your theme root, so just next to your default.hbs
etc. By doing so you enable the service worker to control your whole page (scope: /).
Besides, you can see that I added a version postfix (-v.1.9
). Afaik, Ghost caches your assets heavily and because you cannot use the assethelper here, which automatically prepends a version hash, I do this on my own. Otherwise your service worker file gets cached once and future code changes will be ignored.
While developing it's helpful to enable the "Update on reload"-setting in Chrome's devtools (Devtools -> Application -> Service Workers).