Skip to content
Snippets Groups Projects
service-worker.js 2.13 KiB
Newer Older
self.addEventListener("install", (event) => {
  console.info("Service worker installed.", event)
})

self.addEventListener("activate", (event) => {
  console.info("Service worker activated.", event)
})

const CACHE_NAME = "APP-V0"
const FILES_TO_CACHE = [
  "/index.html",
  "/js/app.js",
  "/logo.png",
  "/manifest.json",
  "/assets/fonts/martel-v4-latin/martel-v4-latin-regular.eot",
  "/assets/fonts/martel-v4-latin/martel-v4-latin-regular.svg",
  "/assets/fonts/martel-v4-latin/martel-v4-latin-regular.ttf",
  "/assets/fonts/martel-v4-latin/martel-v4-latin-regular.woff",
  "/assets/fonts/martel-v4-latin/martel-v4-latin-regular.woff2",
  "/synchronising.svg",
  "/synchronised.svg",
  "/quality-high.svg",
  "/quality-medium.svg",
  "/quality-low.svg",
Nayeem Rahman's avatar
Nayeem Rahman committed
const FILE_ALIASES = new Map([["/", "/index.html"]])
Nayeem Rahman's avatar
Nayeem Rahman committed
self.addEventListener("install", async () => {
  const cache = await caches.open(CACHE_NAME)
  const additions = cache.addAll(FILES_TO_CACHE)
  await additions
  console.info(`Files cached: [\n  ${FILES_TO_CACHE.join(`,\n  `)}\n]`)
})

Nayeem Rahman's avatar
Nayeem Rahman committed
self.addEventListener("activate", async () => {
  const oldCacheKeys = (await caches.keys()).filter((key) => key != CACHE_NAME)
  oldCacheKeys.forEach((key) => caches.delete(key))
})

const normalizePath = (path) => {
  let normalizedPath = path.replace(/\/+/g, "/").replace(/$(?<!^)\/$/, "")
  normalizedPath = FILE_ALIASES.get(normalizedPath) || normalizedPath
  return normalizedPath
}

self.addEventListener("fetch", (event) => {
  let response = fetch(event.request)
  const { origin, pathname } = new URL(event.request.url)
  const path = normalizePath(pathname)
  if (origin == self.location.origin && FILES_TO_CACHE.includes(path)) {
    const requestOptions = { ...event.request, mode: "same-origin" }
    const request = new Request(`${origin}${path}`, requestOptions)
    response.then(async (response) => {
      const clone = response.clone()
      ;(await caches.open(CACHE_NAME)).put(request, clone)
    })
    response = response.catch(async (error) => {
      return (await caches.match(request)) || Promise.reject(error)
    })
Nayeem Rahman's avatar
Nayeem Rahman committed
  event.respondWith(response)