I have a simple Service Worker implementation like this:
JavaScript
x
30
30
1
var CACHE_NAME = "app-cache-v1";
2
var urlsToCache = ["./style/main.css", "./app.ts.js"];
3
4
self.addEventListener("install", function(event) {
5
event.waitUntil(
6
caches.open(CACHE_NAME).then(function(cache) {
7
return cache.addAll(urlsToCache);
8
})
9
);
10
});
11
self.addEventListener("activate", function(event) {
12
event.waitUntil(
13
caches.keys().then(function(cacheNames) {
14
return Promise.all(
15
cacheNames.map(function(cacheName) {
16
return caches.delete(cacheName);
17
})
18
);
19
})
20
);
21
});
22
23
self.addEventListener("fetch", function(event) {
24
event.respondWith(
25
fetch(event.request).catch(function() {
26
return caches.match(event.request);
27
})
28
);
29
});
30
My goal is to cache all resources except the two files indicated in the urlsToCache
variable, these two files should ALWAYS be requested from the network.. How can i achieve this? How can I then verify that it is actually so?
Advertisement
Answer
You can check the url of the request in fetch event handler before deciding what caching strategy to use:
JavaScript
1
12
12
1
self.addEventListener("fetch", function(event) {
2
const url = new URL(event.request.clone().url);
3
if (urlsToCache.indexOf(url.pathname) !== -1) { // check if current url exists in your array
4
event.respondWith(
5
// without cacheing
6
);
7
} else {
8
event.respondWith(
9
// with cacheing
10
);
11
}
12