I have successfully set up a service worker to cache all requests for offline use, but I am experiencing a problem. Every time I load a page, two requests are hitting my webserver: one from the service worker and one from the browser!
How can I cache the request and only load the page once?
This is the code for my service-worker.js file:
self.addEventListener('install', function(event) {
// Load error page which will show if user has no internet
var errorPage = new Request('/?p=error&offline');
event.waitUntil(pushToCache(errorPage));
});
// If any fetch fails, it will look for the request in the cache and serve it from there first
self.addEventListener('fetch', function(event) {
event.waitUntil(pushToCache(event.request));
event.respondWith(
fetch(event.request) // Try loading from internet
.catch(function (error) {
return fetchFromCache(event.request);
}) // No internet connection, try getting it from cache
);
});
function pushToCache(request){
if(request.method == "GET"){
return caches.open('stm-app').then(function (cache) {
return fetch(request).then(function (response) {
return cache.put(request, response);
});
});
}
};
function fetchFromCache(request) {
return caches.open('stm-app').then(function (cache) {
return cache.match(request).then(function (matching) {
if(!matching || matching.status == 404){
return fetchFromCache(new Request('/?p=error&offline')); // Show page that user is offline
}else{
return matching;
}
});
});
}
And this is the content of my sw-register.js file:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('service-worker.js')
.then(function(registration) {
console.log('Registered:', registration);
})
.catch(function(error) {
console.log('Registration failed: ', error);
});
}