Caching of index.html in Angular Service worker

前端 未结 2 629
迷失自我
迷失自我 2021-01-05 04:44

Everytime I make any change to the index.html with my angular project, Serviceworker never gets updated and always serves the old cached version on index.html. How do I fix

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-05 05:29

    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.

提交回复
热议问题