70 %
Chris Biscardi

Service Workies Notes

.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)

JS
self.skipWaiting()
self.addEventListener("activate", () => {
console.log("new SW activated immediately");
})

Detecting if a bad service worker has been replaced

JS
navigator.serviceWorker.addEventListener(
"controllerchange", () => {
console.log("the new worker has taken over");
})

Chapter 3: Intercepting Requests

JS
self.addEventListener("fetch", event => {
console.log(event.request.url);
})

Intercepting

JS
self.addEventListener("fetch", event => {
event.respondWith(new Response("hello!"))
})

Force a worker on the first load. May miss some requests

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

Chapter 4: Caches

JS
self.addEventListener("activate", event => {
event.waitUntil(
caches.open("kolohe-cache")
)
})

Add items to cache

JS

Get items from cache

JS
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

JS
const version = 3;