2

Question

Is it possible to precache a file using a different strategy? i.e. Stale While Revalidate?

Or, should I just load the script in the DOM and then add a route for it in the worker with the correct strategy?

Background

This is quite a weird case so I will try to explain it as best I can...

  • We have two repos; The PWA and The Games
  • Both are statically hosted on the same CDN
  • Due to the Games repo being separate, the PWA has no access to the versioning of the game js bundles
  • Therefore, the solution I have come up with is to generate an unversioned manifest (game-manifest.js) in the Games build
  • The PWA will then precache this file, loop through it's contents, and append each entry to the existing precache manifest
  • However, given the game-manifest.js has no revision and is not hashed, we need to apply either a Network First, or Stale While Revalidate strategy in order for the file to be updated when new versions become available

See the following code as a clearer example of what I am trying to do:

import { precacheAndRoute } from 'workbox-precaching';

// Load the game manifest
// THIS FILE NEEDS TO BE PRECACHED, but under the strategy
// of stale while revalidate, or network first.
importScripts('example.cdn.com/games/js/game-manifest.js');

// Something like...
self.__gameManifest.forEach(entry => {
    self.__precacheManifest.push({
        url: entry
    });
});

// Load the assets to be precached
precacheAndRoute(self.__precacheManifest);
Ben Carey
  • 16,540
  • 19
  • 87
  • 169

1 Answers1

2

Generally speaking, it's not possible to swap in an alternative strategy when using workbox-precaching. It's always going to be cache-first, with the versioning info in the precache manifest controlling how updates take place.

There's a larger discussion of the issue at https://github.com/GoogleChrome/workbox/issues/1767

The recommended course of action is to explicitly set up runtime caching routes using the strategy that you'd prefer, and potentially "prime" the cache by adding entries to it in advance during the install step.

Jeff Posnick
  • 53,580
  • 14
  • 141
  • 167
  • Thank you very much for this Jeff! I feared this would be the case, but having read through the link you posted, I now understand why. Given the unique use case I have outlined, would you be able to provide a little more guidance as to what you would do? For instance, would you have similar code to what I have posted, and then just define a runtime cache route later on? Would that even work? i.e. would it be able to recognise that `example.cdn.com/games/js/game-manifest.js` has already been loaded? Can you give an example of 'priming' the cache in the `install` step? – Ben Carey Sep 11 '19 at 10:59