I'm trying to cache a single page webapp with a service worker. It should get all it's files from the cache and update that cache only when a new service worker-version is published.
With a precache function i'm writing some files to the cache as follows:
function precache() {
return caches.open(CACHE).then(function(cache) {
return cache.addAll([
'index.html',
'js/script.js',
'img/bg.png',
'img/logo.svg',
...
]);
});
}
(I've tried to cache with and without "/" before the paths, and even with absolute paths. Makes no difference)
In Chrome's Cache Storage, the content of all those files is exactly as it should be. But when I try to serve the files from cache on reload of the page, none of the requests match with the cache, they all get rejected, even when I'm still online.
self.addEventListener('fetch', function(evt) {
evt.respondWith(
caches.match(evt.request).then(function(response) {
if(response){
return response;
} else {
reject('no result');
}
}).catch(function(){
if(evt.request.url == 'https://myurl.com'){
return caches.match('/index.html');
}
});
)
});
The index.html from the catch-function gets served correctly, and in turn requests the other files, like /js/script.js. Those request show up like this in the console:
Request { method: 'GET', url: 'https://myurl.com/js/script.js', ... referrer: 'https://myurl.com' }
But they do not return a response, only a notice like this shows:
The FetchEvent for "https://myurl.com/js/script.js" resulted in a network error response: an object that was not a Response was passed to respondWith().
Am I missing something here?
.match
doesn't return a failed promise. If there is not a match it resolves toundefined
. You can probably just move yourcatch
to thethen
block withif (!response && url == 'https://myurl.com') and then
else return response` – Rajit