Service worker

ServiceWorker Cookbook

Getting started with Workbox

Include this inside your Service Worker file (e.g. sw.js)

importScripts('<https://storage.googleapis.com/workbox-cdn/releases/5.0.0/workbox-sw.js>');

if (workbox) {
  console.log(`Yay! Workbox is loaded 🎉`);
} else {
  console.log(`Boo! Workbox didn't load 😬`);
}

Caching

Cache Handling Using Service Workers and the Cache API - Medium article

Calculate total cache storage

let keys = await caches.keys()
let cachesStorage = []

let promises = keys.map(async key => {
  const cache = await caches.open(key)
  const cachedResources = await cache.keys()
  let storage = 0

  for (const request of cachedResources) {
    const response = await cache.match(request)
    const blob = await response.blob()
    storage += blob.size
  }
  return cachesStorage.push({name: key, storage})
})

await Promise.all(promises)
console.table(cachesStorage)

Workbox Precaching

workbox.precaching.precacheAndRoute(['/', 'index.html'], 'GET');

Workbox Caching Strategies

Workbox Strategies With Examples and Use Cases - Medium article

<aside> 💡 Default Cache Strategy is CacheFirst

</aside>