Service Worker

From Logic Wiki
Jump to: navigation, search


Add the Service Worker code

First, we're going to write a new JavaScript file. Let's copy the bare minimum code into a new file-

/** An empty service worker! */
self.addEventListener('fetch', function(event) {
  /** An empty fetch handler! */
});

Save this as sw.js! That's it, you're done! You've created a service worker! 🎆

Register the Service Worker

There's another step. The above code and file (sw.js) isn't referenced anywhere. You'll have to register it imperatively, i.e., inside your site's code.

Assume site already includes a script that's run by every page in the site. Open up site.js (another file that starts off empty), and add the registration code-

navigator.serviceWorker && navigator.serviceWorker.register('./sw.js').then(function(registration) {
  console.log('Excellent, registered with scope: ', registration.scope);
});

That's it! This code will execute on every page load. If the Service Worker is actually already registered, your browser will ignore the request and check if it's changed at some later point.

Be sure to reload your page and then check chrome://serviceworker-internals/ to ensure that it's actually loaded for the site. It should look like this-