Service-worker force update of new assets

后端 未结 3 1843
灰色年华
灰色年华 2020-12-05 00:13

I\'ve been reading through the html5rocks Introduction to service worker article and have created a basic service worker that caches the page, JS and CSS which works as expe

相关标签:
3条回答
  • 2020-12-05 00:22

    One way of invalidating the cache would be to bump version of the CACHE_NAME whenever you change anything in the cached files. Since that change would change the service-worker.js browser would load a newer version and you'd have a chance to delete the old caches and create new ones. And you can delete the old cache in the activate handler. This is the strategy described in prefetch sample. If you already using some kind of version stamps on CSS files make sure that they find their way into service worker script.

    That of course does not change the fact that cache headers on CSS file need to be set correctly. Otherwise service worker will just load the file that is already cached in browser cache.

    0 讨论(0)
  • 2020-12-05 00:26

    One option is just to use a the service worker's cache as a fallback, and always attempt to go network-first via a fetch(). You lose some performance gains that a cache-first strategy offers, though.

    An alternative approach would be to use sw-precache to generate your service worker script as part of your site's build process.

    The service worker that it generates will use a hash of the file's contents to detect changes, and automatically update the cache when a new version is deployed. It will also use a cache-busting URL query parameter to ensure that you don't accidentally populate your service worker cache with an out-of-date version from the HTTP cache.

    In practice, you'll end up with a service worker that uses a performance-friendly cache-first strategy, but the cache will get updated "in the background" after the page loads so that the next time it's visited, everything is fresh. If you want, it's possible to display a message to the user letting them know that there's updated content available and prompting them to reload.

    0 讨论(0)
  • 2020-12-05 00:36

    A browser caching issue

    The main problem here is that when your new service worker is installing, he fetches requests that are handled by the previous service worker and it's very likely that he's getting resources from cache because this is your caching strategy. Then even though you're updating your service worker with new code, a new cache name, calling self.skipWaiting(), he's still putting in cache the old resources in cache!

    This is how I fully update a Service Worker

    One thing to know is that a service worker will trigger the install event each time your code script changes so you don't need to use version stamps or anything else, just keeping the same file name is okay and even recommended. There are other ways the browser will consider your service worker updated.

    1. Rewrite your install event handler:

    I don't use cache.addAll because it is broken. Indeed if one and only one of your resource to cache cannot be fetched, the whole installation will fail and not even one single file will be added to the cache. Now imagine your list of files to cache is automatically generated from a bucket (it's my case) and your bucket is updated and one file is removed, then your PWA will fail installing and it should not.

    sw.js

    self.addEventListener('install', (event) => {
      // prevents the waiting, meaning the service worker activates
      // as soon as it's finished installing
      // NOTE: don't use this if you don't want your sw to control pages
      // that were loaded with an older version
      self.skipWaiting();
    
      event.waitUntil((async () => {
        try {
          // self.cacheName and self.contentToCache are imported via a script
          const cache = await caches.open(self.cacheName);
          const total = self.contentToCache.length;
          let installed = 0;
    
          await Promise.all(self.contentToCache.map(async (url) => {
            let controller;
    
            try {
              controller = new AbortController();
              const { signal } = controller;
              // the cache option set to reload will force the browser to
              // request any of these resources via the network,
              // which avoids caching older files again
              const req = new Request(url, { cache: 'reload' });
              const res = await fetch(req, { signal });
    
              if (res && res.status === 200) {
                await cache.put(req, res.clone());
                installed += 1;
              } else {
                console.info(`unable to fetch ${url} (${res.status})`);
              }
            } catch (e) {
              console.info(`unable to fetch ${url}, ${e.message}`);
              // abort request in any case
              controller.abort();
            }
          }));
    
          if (installed === total) {
            console.info(`application successfully installed (${installed}/${total} files added in cache)`);
          } else {
            console.info(`application partially installed (${installed}/${total} files added in cache)`);
          }
        } catch (e) {
          console.error(`unable to install application, ${e.message}`);
        }
      })());
    });
    

    2. Clean the old cache when the (new) service worker is activated:

    sw.js

    // remove old cache if any
    self.addEventListener('activate', (event) => {
      event.waitUntil((async () => {
        const cacheNames = await caches.keys();
    
        await Promise.all(cacheNames.map(async (cacheName) => {
          if (self.cacheName !== cacheName) {
            await caches.delete(cacheName);
          }
        }));
      })());
    });
    

    3. I update the cache name every time I have updated my assets:

    sw.js

    // this imported script has the newly generated cache name (self.cacheName)
    // and a list of all the files on my bucket I want to be cached (self.contentToCache),
    // and is automatically generated in Gitlab based on the tag version
    self.importScripts('cache.js');
    
    // the install event will be triggered if there's any update,
    // a new cache will be created (see 1.) and the old one deleted (see 2.)
    

    4. Handle Expires and Cache-Control response headers in cache

    I use these headers in the service worker's fetch event handler to catch whether it should request the resource via the network when a resource expired/should be refreshed.

    Basic example:

    // ...
    
    try {
      const cachedResponse = await caches.match(event.request);
    
      if (exists(cachedResponse)) {
        const expiredDate = new Date(cachedResponse.headers.get('Expires'));
    
        if (expiredDate.toString() !== 'Invalid Date' && new Date() <= expiredDate) {
          return cachedResponse.clone();
        }
      }
    
      // expired or not in cache, request via network...
    } catch (e) {
      // do something...
    }
    // ...
    
    0 讨论(0)
提交回复
热议问题