Skip to content
Snippets Groups Projects
service-worker.js 1.64 KiB
Newer Older
  • Learn to ignore specific revisions
  • 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",
    ]
    
    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) => {
          await (await caches.open(CACHE_NAME)).put(request, response.clone())
        })
        response = response.catch(async (error) => {
          return (await caches.match(request)) || Promise.reject(error)
        })
    
    Nayeem Rahman's avatar
    Nayeem Rahman committed
      event.respondWith(response)