I have just attempted to implement service workers to cache some JSON files and other assets on a static site (running on localhost chrome Version 47.0.2526.73 (64-bit)). Us
If you don't see the mark from service worker then your page is not controlled by the service worker yet (you can check by inspecting navigator.serviceWorker.controller in the client page). The default behaviour for a page is to become controlled the next time you visit it after SW activation so you have two options:
self.skipWaiting() and self.clients.claim() methods during installation and activation respectively to force the service worker to take control of the clients ASAP.Look at the Service Worker Cookbook, it includes an JSON cache recipe.
Once you fix the problem with control, you need to fix your handler. I think you want to apply a policy of cache-first. If not in cache, then go to network and fill the cache. To do that:
self.onfetch = function (event) {
var req = event.request;
return event.respondWith(function cacheFirst() {
// Open your cache.
return self.caches.open('v1').then(function (cache) {
// Check if the request is in there.
return cache.match(req).then(function (res) {
// If not match, there is no rejection but an undefined response.
if (!res) {
// Go to network.
return fetch(req.clone()).then(function (res) {
// Put in cache and return the network response.
return cache.put(req, res.clone()).then(function () {
return res;
});
});
}
return res;
});
});
});
}