Reputation: 1842
I have some service workers that work as expected, mainly fetching, caching and requesting content as instructed.
However I've noticed that additional to the designated content, say files/folders that are declared in the service worker, non declared content is added to the cache, while navigating in the domain.
This, by the way is an issue, it bloates the cache space, and in general I don't want it to be cached.
How can the addition of non declared content by a Service Worker content be stopped while navigating under a domain?
Here is the installation code of th SW, which is responsible for adding content.
// Declaring cache name, version, files to be cached.
self.addEventListener('install', function(e) {
console.log('[ServiceWorker] Install');
e.waitUntil(
caches.open(CACHE_NAME).then(function(cache) {
console.log('[ServiceWorker] DTL Install Caching App Shell');
return Promise.all([cache.addAll(FILES_TO_CACHE)]);
}).then(function() {
//skiWaiting, forza instalacion de SW.
return self.skipWaiting();
})
);
});
And while navigating to additional folders of the domain, but not declared in the content-to-be-cached array, as usual the fetch event is triggered, which code is this:
self.addEventListener('fetch', function(event) {
console.log('SW DTL fetch');
event.respondWith(
caches.open(CACHE_NAME).then(function(cache) {
return fetch(event.request).then(function(response) {
cache.put(event.request, response.clone());
return response;
});
})
);
});
Upvotes: 1
Views: 97
Reputation: 3200
You do not have to prevent anything since Service Worker by default does not add items to cache automatically. You are actually adding items to the cache manually using Cache.put() method in your fetch
handler.
What you should be using is Cache.match() instead;
event.respondWith(
caches.match(event.request).then(function (response) {
// return the response if it is found in cache
if (response) return response;
// fall back to network as usual otherwise
console.log('SW: No response found in cache. About to fetch from network...');
return fetch(event.request).then(function (response) {
return response;
});
})
);
Upvotes: 4