.ready serviceWorker shortcut
navigator.serviceWorker.controller is a shortcut to the currently active Service Worker (if the Worker is in control of the page and not just active)
How to force a new service worker: (danger)
self.skipWaiting()self.addEventListener("activate", () => {console.log("new SW activated immediately");})
Detecting if a bad service worker has been replaced
navigator.serviceWorker.addEventListener("controllerchange", () => {console.log("the new worker has taken over");})
self.addEventListener("fetch", event => {console.log(event.request.url);})
Intercepting
self.addEventListener("fetch", event => {event.respondWith(new Response("hello!"))})
Force a worker on the first load. May miss some requests
self.addEventListener("activate", event => {event.waitUntil(clients.claim())})
self.addEventListener("activate", event => {event.waitUntil(caches.open("kolohe-cache"))})
Add items to cache
Get items from cache
self.addEventListener("fetch", event => {event.respondWith(caches.open("kolohe-cache").then(cache => {return cache.match(event.request.url).then(res => {return res || fetch(event.request.url)})}))})
Deleting and versioning
const version = 3;