Intro to Service Workers

Goals:

  1. Understand when and why to use service workers
  2. Be able to implement service workers for making application assets available offline

What is a Service Worker?

a new API that allows you to run a script in background of your application and facilitates creating
Progressive Web Apps

What can Service Workers do?

  • offline your application
  • implement background sync*
  • enable push notifications*

Characteristics of a Service Worker

Runs in the background

  • web workers are single JavaScript files, run on own thread
  • don't block execution of other client-side code
  • handle time-intensive operations without locking UI
  • service workers are a type of web worker
  • service workers allow background processing that specifically relates to handling network requests

Cannot interact with DOM

  • can't access the DOM tree to do any manipulations
  • must communicate through sending messages back and forth

Event-based

  • service worker can 'go to sleep' at any time
  • is only woken up and utilized during events

Read: What's the Difference Between Service Workers, Web Workers, and Web Sockets?

Let's Practice

First things first:

1. Unregister any pre-existing service workers

2. Clear any cache storages you've created in the past

Clone this repo

`npm install`

`npm start`

`http://localhost:3000`

Service Worker Lifecycle

1. Registration: browser is aware that we have a service worker that needs to be recognized, and will kick off the installation step upon a successful registration

2. Installation: the service worker is installed, but doesn’t actually control anything on the page just yet. This is a good phase to cache assets for offline use.

3. Activation: the service worker has been installed and is activated. This is a good place for us to manage old cached assets and update the service worker.

4. Full Page Control: the service worker has been activated and now has full control over any pages that fall under its scope