Skip to content

Instantly share code, notes, and snippets.

@Duske
Created November 11, 2016 21:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Duske/5214b72972e906e32edc107c2453257e to your computer and use it in GitHub Desktop.
Save Duske/5214b72972e906e32edc107c2453257e to your computer and use it in GitHub Desktop.
Ghost blog - Service worker starting

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.hbsetc. 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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment