Register
1 | navigator.serviceWorker.register('your_service_worker,js', { scope: 'your_path_name' }) |
Unregister
1 | navigator.serviceWorker.getRegistration('your_service_worker.js', { scope: 'your_path_name' }) |
Worker.js
1 | self.addEventListener('install', (event) => { |
LifeCycle
Download and Parse
After registration of Service Worker, browser will download and parse the script from specified url.
1 | /* In main.js */ |
Installing
After successfully parsed, browser will install the Service Worker. Once the Install finished, the worker will emit install
event, and waiting for activating
. If the install failed, Service Worker will be Redundant
1 | /* In sw.js */ |
If there is an event.waitUntil(promiseObj)
method in the event, the installing event will not be successful until the Promise within it is solved. If the Promise is rejected, the install event fails and the Service Worker became redundant
Installed / Waiting
If the installation is successful, the Service Worker moves to the installed(also called waiting) state. In this state it is a valid, but not yet active, worker. It is not yet in control of the document., but rather is waiting to take control form the current worker.
Activating
The activating state will be triggered for a waiting Service Worker in one of the following scenarios -
if there is no current active worker already
if the
self.skipWaiting()
method is called in the Service Worker scriptif the user has navigated away from the page, thereby releasing the previous active worker.
if a specified period of time has passed, thereby releasing the previous active worker
During the activating state, the active event in the Service Worker script is carried out. In a typical activate event, we clear files from old caches.
1 | /* In sw.js */ |
Activate
If the worker is activated, it will emit active
event, and take over all fetch from page. If active failed, the worker will be Redundant
Redundant
Once a worker is redundant, it won’t have effect on page.
Dependencies
fetch
promise
CacheStorage: store Cache Object
Cache: store Request/Response Pair Object
Example: Cache Static Resource
listen to install to cache static resource
listen to fetch to intercept request and return cached static Resource
1 | var CACHE_NAME = 'my-site-cache-v1' |
Version Controls
1 | var deleteObsoleteCache = () => { |
Whitelist
1 | // resource whitelist |