How to update service worker cache in PWA?

Ildar picture Ildar · Jun 19, 2017 · Viewed 11.7k times · Source

I use service worker with sw-toolbox library. My PWA caches everything except API queries (images, css, js, html). But what if some files will be changed someday. Or what if service-worker.js will be changed. How application should know about changes in files?

My service-worker.js:

'use strict';
importScripts('./build/sw-toolbox.js');

self.toolbox.options.cache = {
  name: 'ionic-cache'
};

// pre-cache our key assets
self.toolbox.precache(
  [
    './build/main.js',
    './build/main.css',
    './build/polyfills.js',
    'index.html',
    'manifest.json'
  ]
);

// dynamically cache any other local assets
self.toolbox.router.any('/*', self.toolbox.cacheFirst);

// for any other requests go to the network, cache,
// and then only use that cached resource if your user goes offline
self.toolbox.router.default = self.toolbox.networkFirst;

I don't know what is the usual method to update cache in PWA. Maybe PWA should send AJAX request in background and check UI version?

Answer

Chris Love picture Chris Love · Jun 19, 2017

AFAIK the sw_toolbox does not have a strategy for cache with network update. This is really what you want I think. You want to modify the cache-network race strategy - > https://jakearchibald.com/2014/offline-cookbook/#cache-network-race Instead of just letting the loser fade away, once the network responds you will want to update the client. This is a little more advanced that I have time or time to explain here. I would post a message to the client to let it know there is an update. You may want to alert the user to the update or just force the update. I don't consider this to be an edge case, but a very common, but advanced scenario. I hope to publish a more detailed solution soon.