google-analyticsprogressive-web-appsservice-workerbrowser-cachecachestorage

Cache is building up with each load


I am working on my portfolio website. It is a PWA and there is a service worker. I am caching the index page and all the required assets of the index page using the service worker. But when I actually test it the cache size is building up with each load. After some experiments I found out that the problem is with the Google analytics script though I am not sure. But I cannot find a way to fix it. I had copied directly the code from Google analytics. Then as it didn't work, I tried to set the crossorigin="anonymous". Then also it isn't working.

Source code

Thanks in advance!


Solution

  • Right now your service worker's fetch handler unconditionally applies a caching strategy to all requests, regardless of what server is invovled.

    If you want to avoid applying that strategy to requests made to third-party servers, like Google Analytics, you can exit the fetch handler early, before you call event.respondWith(). If you do that, then the normal network behavior will still apply, and you won't get any of the caching.

    Assuming all of the assets that you want to cache are served from the same-origin server, you can do this with:

    self.addEventListener('fetch', (event) => {
      const url = new URL(event.request.url);
      if (url.origin !== location.origin) {
        return;
      }
    
      // event.respondWith() and the caching logic goes here.
    });