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:
2nd load of page:
I'd be grateful for any advice on what I'm doing wrong, or how to debug it.
Thanks in advance
Dan
clientsClaim
means that your service worker will take control of a page as soon as the SWactivate
s, but it does take time for that activation to happen (it has to complete theinstall
step first). If your API request is made before the SW takes control, it's not going to be picked up and cached until a subsequent visit. I went to your site and confirm that on the second visit, without hard reloads, the runtime cache is populated. – Crosscrossletwindow.caches.open('my-cache').then(cache => cache.add(requestUrl));
from your page should do it. When you set up your SW strategy, useworkboxSW.strategies.staleWhileRevalidate({cacheName: 'my-cache'});
so that it uses the same cache. – Crosscrosslet