1

I'm thinking of using Google's Workbox to pre-cache a bunch of files, and I've been scratching my head as to how to generate unique hashes for files when they change. Something like this:

 workbox.precaching.precacheAndRoute([
    { 
      url: '/',
      revision: '383676',
    },
    { 
      url: '/about',
      revision: 213142,
    },
    { 
      town: '/location',
      revision: 742125,
    },
  ]);

Ideally the revision number would change when the entry or related entries included in the page are changed/saved. I got this working but I'm not sure how to get related content to clear the cache:

// service-worker.js

{%- cache using key 'abc' -%}
    { 
      url: {{ craft.entries.id(64).one.uri }},
      revision: {{ random(100000, 999999) }},
    },
{%- endcache -%}

This seems to work when said entry is saved, but I'm not sure how to deal with a related entry being saved. I'm also not sure this is the most performant way to go.

1

So you shouldn't try to come up with a hashed file naming scheme for busting the cache; instead use one of Workbox's Strategies -- I think a great pattern for what you're trying to do is Stale While Revalidate

TL;DR Workbox has strategies for doing what you're trying to do.

| improve this answer | |
  • Thanks Andrew, but this is what I'm wondering: does re-validating mean going back to the server and requesting the page (and querying the DB) even if the page hasn't changed? I'd imagine that with a manifest, if the hashed file hasn't changed, then the SW would simply serve from the cache and stay away from the server until instructed to do so. – Paul Jun 15 '19 at 3:17
  • There are many strategies you can adopt... my point is really that Workbox can handle this for you, you're not going to need template logic. – andrew.welch Jun 24 '19 at 18:58
  • It took me a while to wrap my head around all this, but the precache manifest is useful primarily for static assets (js, css...). In my case, stale-while-revalidate is probably the way to go for content, provided I can workout how to refresh the page when new content is available. – Paul Jun 26 '19 at 1:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.