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')
- Fetch sw.js
- Install worker
- 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')
- Fetch sw.js
- Install worker
- Activate worker
- 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()
- Fetch sw.js
- Check diff
- Install new worker
-
Set worker waiting
- Wait for closing all clients
- Demo
- Register => Generate => Update => Test
.waiting
skipWaiting()
Activate worker immediately
- registration.update()
- Fetch sw.js
- Check worker version
- Install worker
- skipWaiting()
- 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
-
on install: Emergency Update
active vs controller
- window-side concern:
- Only page's control
- FYI: oncontrollerchange, onupdatefound
- Only page's control
- worker-side concern:
- Only worker's state
- installing / waiting / active
- Only worker's state
-
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
- Installed worker won't be activated
Links
Service Worker Lifecycle
By Suguru Inatomi
Service Worker Lifecycle
pwa_study
- 6,590