javascriptservice-workeroffline-caching

Why is my web page slow when serving offline using service worker caches?


I'm trying to make my webpage work completely offline, but I'm running into some issues with load time when trying to load from the cache

I'm currently caching all the files necessary for my website to run (about ~640kB in size, ~24 various text files), however the load time, when offline or online, is up to 2 minutes (or sometimes just completely times out, giving me this error: Error: {"columnNumber":-1,"lineNumber":-1,"message":"ServiceWorker startup timed out. The worker was in startup phase: Script streaming.","sourceURL":""})

(It loads just fine, even faster, without the caching.)

I've tried specifying which files to serve, as well as unregistering and reregistering the service worker multiple times.

The code for the service worker is below:

const CACHE_NAME = "webedit-testing-v2";

self.addEventListener('install', event => {
  console.log("Service worker: Installed.")

  self.skipWaiting()
})

self.addEventListener('activate', event => {
  console.log('Service worker: Activated.')

  event.waitUntil(
    caches.keys().then(cacheNames => {
      return Promise.all(
        cacheNames.map(cache => {
          if (cache !== CACHE_NAME) {
            console.log('Service worker: Deleting old caches.')
            caches.delete(cache)
          }
        })
      )
    })
  )
})

self.addEventListener('fetch', event => {
  console.log(`Service worker: Fetching ${event.request.url}`)
  event.respondWith(
    fetch(event.request)
      .then(res => {
        const resClone = res.clone()
        caches.open(CACHE_NAME)
          .then(cache => {
            cache.put(event.request, resClone)
          })
          return res
      })
      .catch(() => caches.match(event.request).then(res => res))
  )
})

Solution

  • Update: It turns out the slowness seems to have been caused by my ad blocker extension (Adblock Plus) (Thank you Why chrome cached requests are taking time?), after disabling it, the site loads perfectly fine.

    (It also turns out this was happening to other cached sites I had on my computer.)