d_a_n
d_a_n

Reputation: 317

Workbox - runtime cache only created on second page refresh

I'm new to service workers, and I'm using Workbox to precache my app shell and cache my api data.

The precaching of assets is working correctly, with the cache being created and populated.

The runtime caching isn't creating a cache and populating it until I reload the page a second time.

I thought this might be a timing issue, so I set a page reload of the data in the javascript, however this still didn't cache the call.

I'm not doing anything specific to create the cache, app code is:

...
app.getData = function() {
  var requestHeaders = new Headers({
    Accept: "application/json"
  });
  fetch(app.dataUrl, { headers: requestHeaders })
  .then(function(response) {
    return response.json();
  })
  .then(function(json) {
      app.updateCards(json);
  })
  .catch(function(error) {
      console.log('There has been a problem with your fetch operation: ' + error.message);
  });
}
...
if ('serviceWorker' in navigator) {
navigator.serviceWorker
         .register('/my_sw.js')
         .then(function() {
            console.log('Service Worker Registered');
         });
}

app.getData();  # fetch api data

then in the service worker:

 ...
 const workboxSW = new self.WorkboxSW({clientsClaim: true});
 // register data url to cache
 workboxSW.router.registerRoute(
    '/my_api/data',
     workboxSW.strategies.staleWhileRevalidate()
 );
 // pre-cache assets
 workboxSW.precache(fileManifest);

I am using the Chrome Dev tools to check the sw status and the cache created. The network calls to the data URL are as follows:

1st load of page:
enter image description here 2nd load of page:
enter image description here

I'd be grateful for any advice on what I'm doing wrong, or how to debug it.

Thanks in advance
Dan

Upvotes: 9

Views: 3549

Answers (1)

Matt Gaunt
Matt Gaunt

Reputation: 9821

To be safe, you might want to add skipWaitingto the Workbox constructor to ensure the service worker doesn't wait for the page to reload to start caching.

You would also want to wait on serviceWorker.ready in your page before making the API call. This way you know the service worker is active.

These changes together, in your service worker you would have:

 ...
 const workboxSW = new self.WorkboxSW({skipWaiting: true, clientsClaim: true});
 // register data url to cache
 workboxSW.router.registerRoute(
    '/my_api/data',
     workboxSW.strategies.staleWhileRevalidate()
 );
 // pre-cache assets
 workboxSW.precache(fileManifest);

Then in your web page

...
if ('serviceWorker' in navigator) {
    navigator.serviceWorker
      .register('/my_sw.js')
      .then(function() {
        return navigator.serviceWorker.ready;
      })
      .then(function() {
        app.getData();  # fetch api data
      });
}

Upvotes: 5

Related Questions