What is a Service Worker?

Service Worker is simply a JavaScript file that sits between you and the network.
It’s a type of web worker that runs separately from your page. It can’t access the DOM, but it can control pages by intercepting requests as the browser makes them and do whatever you want with them.

What Happens in a Service Worker?
You listen for particular events and react to them.

  1. You register for a Service Worker by giving the location of your SW script.
    navigator.serviceWorker.register('/sw.js')
  2. A promise is returned; you get a callback for failure of success.
    navigator.serviceWorker.register('/sw.js').then(function(reg) { 
      console.log('Yay!');
    }).catch(function(err) {
      console.log('Boo!');
    });

     

  3. You can also provide a scope. The SW will control any page whose URL begins with that scope.
    navigator.serviceWorker.register('/sw.js', {
      scope: '/my-app/'
    });
    

     

Scopes

You can have a service worker that controls multiple scopes, which is really handy when you have multiple projects share the same origin.
Given this registration code:

navigator.serviceWorker.register('/sw.js', {scope: '/foo/'});

This service worker will control the URLS in bold:
/
/sw.js
/foo
/foo.html
/foo/
/foo/bar/index.html
/foo/bar