1

instead of a hard coded list of urls in serviceworker.js

workbox.precaching.precacheAndRoute([
  { url: '/index.php',revision: 'index2209'},
  { url: '/images/wifino.svg',revision: 'wifino2209'},
  { url: '/offline.php',revision: 'offline2209'}
]);

I want to add the urls dynamic with a json file (generated with PHP). The json file looks like this (but can be changed):

{url: 'm.php?tid=1', revision: '11579804421'},
{url: 'm.php?sid=17', revision: '21579804421'},
{url: 'm.php?sid=3', revision: '31579804421'}

How can I read this file and put it to the list of workbox.precaching.precacheAndRoute?

Thanks a lot!

Uli

1 Answer 1

0

You really can't do that with workbox-precaching. It relies on the revision information being stored inline within the top-level service worker file, so that any changes to a revision field will trigger the update process in the service worker lifecycle. This is an optimization that avoids needing to have to revalidate precached URLs outside of the install event.

One way of working around this might be to configure your web server to dynamically generate your service-worker.js contents, and insert whatever the appropriate precache manifest versioning info would be into the call to workbox.precaching.precacheAndRoute(). It's been a while since I've worked with PHP so I can't come up with some sample code off the top of my head, but you'd basically want to use whatever logic you use to generate your JSON and instead of writing it to a separate file, echo its contents into your service-worker.js.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, Jeff, for your answer. Dynamically generate my service-worker.js is possible. The idea behind is that I want to cache the last 10 news when a user installs the app. What would happens when the SW.js is brand new every hour or so? Is this a problem?
I wouldn't necessarily use precaching for that sort of thing. Setting up a runtime caching route and priming the cache might be a better approach: developers.google.com/web/tools/workbox/guides/route-requests and developers.google.com/web/tools/workbox/guides/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.