Service Worker
Lifecycle

2017-09-14

laco

about me

  • Kaizen Platform
    • We're hiring!
  • ng-japan Organizer
  • <3 PWA

Service Worker Lifecycle

Installation & Activation

The intent

  • For offline-first
  • For safe migration
  • For consistency

Window-side APIs

if ('serviceWorker' in navigator) {
    // register service worker
    navigator.serviceWorker.register('/sw.js')
        .then((registration) => {
            registration.update()
                .then(() => {
                    registration.unregister();
                }); 
        });
}

Case 1. The 1st SW

  • register('sw.js')
    1. Fetch sw.js
    2. Install worker
    3. Activate worker
  • The page is not controlled
    • Wait for next 'onload'
  • Demo
    • Unregister => Reload => Register => Test

.active (w/o control)

clients.claim()

Get the page under control

  • register('sw.js')
    1. Fetch sw.js
    2. Install worker
    3. Activate worker
    4. clients.claim()
  • Demo
    • Unregister => Reload => Register => Test

clients.claim() on activate

self.addEventListener("activate", (event) => {
    event.waitUntil(
        self.clients.claim()    
    );
});

w/ clients.claim()

Case 2. Update SW

  • registration.update()
    1. Fetch sw.js
    2. Check diff
    3. Install new worker
    4. Set worker waiting
      • Wait for closing all clients
  • Demo
    • Register => Generate => Update => Test

.waiting

skipWaiting()

Activate worker immediately

  • registration.update()
    1. Fetch sw.js
    2. Check worker version
    3. Install worker
    4. skipWaiting()
    5. Activate worker
  • The worker will be controller immediately
  • Demo
    • Register => Generate => Update => Test

skipWaiting() on install

self.addEventListener("install", (event) => {
    event.waitUntil(
        self.skipWaiting()
    );
});

w/ skipWaiting()

Use-cases

  • clients.claim()
    • Enable offline-mode on the first engagement
  • skipWaiting()
    • on install: Emergency Update
      • Recover broken sw.js releasing
    • on message: Hot Update
      • Update worker as a functionality

active vs controller

  • window-side concern:
    • Only page's control
      • FYI: oncontrollerchange, onupdatefound
  • worker-side concern:
    • Only worker's state
      • installing / waiting / active
  • controller === active worker
    • skipWaiting() will change controller

Flow

Summary

  • The first worker
    • Activated worker won't get control
    • claim(): Get control immediately
  • Update worker
    • Installed worker won't be activated
      • Wait for closing all clients
    • skipWaiting(): Activate worker immediately
      • WARNING:  Worker will be controller

Links

Service Worker Lifecycle

By Suguru Inatomi

Service Worker Lifecycle

pwa_study

  • 6,590