JavaScript A simple service worker


Example

main.js

A service worker is an event-driven worker registered against an origin and a path. It takes the form of a JavaScript file that can control the web page/site it is associated with, intercepting and modifying navigation and resource requests, and caching resources in a very granular fashion to give you complete control over how your app behaves in certain situations (the most obvious one being when the network is not available.)

Source: MDN

Few Things:

  1. It's a JavaScript Worker, so it can't access the DOM directly
  2. It's a programmable network proxy
  3. It will be terminated when not in use and restarted when it's next needed
  4. A service worker has a lifecycle which is completely separate from your web page
  5. HTTPS is Needed

This code that will be executed in the Document context, (or) this JavaScript will be included in your page via a <script> tag.

// we check if the browser supports ServiceWorkers
if ('serviceWorker' in navigator) {
  navigator
    .serviceWorker
    .register(
      // path to the service worker file
      'sw.js'
    )
    // the registration is async and it returns a promise
    .then(function (reg) {
      console.log('Registration Successful');
    });
}

sw.js

This is the service worker code and is executed in the ServiceWorker Global Scope.

self.addEventListener('fetch', function (event) {
  // do nothing here, just log all the network requests
  console.log(event.request.url);
});