Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caching of index.html in Angular Service worker

Everytime I make any change to the index.html with my Angular project, Service Worker never gets updated and always serves the old cached version on index.html. How do I fix this (Also, there is no caching at the server end as well as browser)

Here is my ngsw-config file:

    {
      "index": "/index.html",
      "assetGroups": [{
        "name": "app",
        "installMode": "prefetch",
        "resources": {
          "files": [
            "/favicon.ico",
            "/index.html",
            "/manifest.json"
          ],
          "versionedFiles": [
            "/*.bundle.css",
            "/*.bundle.js",
            "/*.chunk.js"
          ]
        }
      }, {
        "name": "assets",
        "installMode": "lazy",
        "updateMode": "prefetch",
        "resources": {
          "files": [
            "/assets/**"
          ]
        }
      }]
    }

My response headers for the request:

Screenshot of my request to my angular APP

Any idea how to get this fixed?

Thanks

like image 956
Sampat Avatar asked Mar 07 '18 02:03

Sampat


1 Answers

You can force the service worker to delete all previous SW caches (index.html too) with a code like this in the service worker:

const DIRTY_CACHE = 'application-version-number-or-whatever';

self.addEventListener('install', () => { 
  // Skip over the "waiting" lifecycle state, to ensure that our 
  // new service worker is activated immediately, even if there's 
  // another tab open controlled by our older service worker code. 
  self.skipWaiting(); 
});

self.addEventListener('activate', event => {
  self.registration.unregister();
  event.waitUntil(
    caches
      .keys()
      .then(cacheNames =>
        cacheNames.filter(cacheName => cacheName.indexOf(DIRTY_CACHE) !== -1),
      )
      .then(cachesToDelete =>
        Promise.all(
          cachesToDelete.map(cacheToDelete => caches.delete(cacheToDelete)),
        ),
      )
      .then(() => self.clients.claim()),
  );
});

A more detailed explanation can be found in this article

Maybe is not the best strategy, but resolves the issue, probably due to a bad expires header.

like image 200
zarpilla Avatar answered Sep 19 '22 20:09

zarpilla