Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using workbox runtime caching, requests are not showing on cache storage on chrome

I am using workbox runtime caching to cache external calls (materialize.css is one of those). In my network tab it shows that the request is coming from serviceWorker (looks fine):

enter image description here

But on cache storage my runtime cache looks empty:

enter image description here

You can see my service worker on chromes's application tab, and this is the website: https://quack.surge.sh/

Service worker code:

const workboxSW = new self.WorkboxSW();
workboxSW.precache(fileManifest);
workboxSW.router.registerNavigationRoute("/index.html");workboxSW.router.registerRoute(/^https:\/\/res.cloudinary.com\/dc3dnmmpx\/image\/upload\/.*/, workboxSW.strategies.cacheFirst({}), 'GET');
workboxSW.router.registerRoute('https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css', workboxSW.strategies.cacheFirst({}), 'GET');
workboxSW.router.registerRoute('https://res.cloudinary.com/dc3dnmmpx/image/upload/(.*)', workboxSW.strategies.cacheFirst({}), 'GET');

Is this the expected behaviour? I'm pretty new to service workers and I am not sure what is the correct result.

like image 657
Glauber Avatar asked Sep 26 '17 01:09

Glauber


1 Answers

The underlying issue is that those are opaque responses, and by default, they won't be used with a cacheFirst strategy.

There's some background at https://workboxjs.org/how_tos/cdn-caching.html

There's logging in Workbox to help debug this sort of thing, but as it's noisy, it's not enabled by default in the production build. Either switching your importScripts() to use the development build (e.g. importScripts('https://unpkg.com/[email protected]/build/importScripts/workbox-sw.dev.v2.0.3.js'), or going in to DevTools and explicitly setting workbox.LOG_LEVEL = 'debug' would give you a log message like the following:

DevTools log

You have a few options for getting things working as you expect:

  • Change to workboxSW.strategies.staleWhileRevalidate(), which supports opaque response by default.
  • Tell the cacheFirst strategy that you're okay with it using opaque responses: workboxSW.strategies.cacheFirst({cacheableResponse: {statuses: [0, 200]}})
  • Because your third-party CDNs all seem to support CORS, you could opt-in to CORS mode for your CSS and image requests via the crossorigin attribute, and the responses will no longer be opaque: <img src='https://cors.example.com/path/to/image.jpg' crossorigin='anonymous'> or <link rel='stylesheet' href='https://cors.example.com/path/to/styles.css' crossorigin='anonymous'>
like image 127
Jeff Posnick Avatar answered Oct 22 '22 13:10

Jeff Posnick