-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice-worker_old.js
More file actions
99 lines (84 loc) · 2.78 KB
/
Copy pathservice-worker_old.js
File metadata and controls
99 lines (84 loc) · 2.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
var CACHE_VERSION = 1;
var CURRENT_CACHES = {
prefetch: "prefetch-cache-v" + CACHE_VERSION,
font: "font-cache-v" + CACHE_VERSION,
};
self.addEventListener("install", function (event) {
var urlsToPrefetch = ["./", "css", "js"];
// console.log(
// "Handling install event. Resources to pre-fetch:",
// urlsToPrefetch
// );
event.waitUntil(
caches
.open(CURRENT_CACHES["prefetch"])
.then(function (cache) {
return cache.addAll(urlsToPrefetch);
})
.catch(function (error) {
console.error("Pre-fetching failed:", error);
})
);
});
self.addEventListener("activate", function (event) {
var expectedCacheNames = Object.keys(CURRENT_CACHES).map(function (key) {
return CURRENT_CACHES[key];
});
// Active worker won't be treated as activated until promise resolves successfully.
event.waitUntil(
caches.keys().then(function (cacheNames) {
return Promise.all(
cacheNames.map(function (cacheName) {
if (expectedCacheNames.indexOf(cacheName) == -1) {
// console.log("Deleting out of date cache:", cacheName);
return caches.delete(cacheName);
}
})
);
})
);
});
self.addEventListener("fetch", function (event) {
// console.log("Handling fetch event for", event.request.url);
event.respondWith(
caches.match(event.request).then(function (response) {
// Cache hit - return response
if (response) {
return response;
}
return fetch(event.request).then(function (response) {
// Check if we received a valid response
if (!response || response.status !== 200 || response.type !== "basic") {
return response;
}
// IMPORTANT: Clone the response. A response is a stream
// and because we want the browser to consume the response
// as well as the cache consuming the response, we need
// to clone it so we have two streams.
var responseToCache = response.clone();
caches.open(CURRENT_CACHES["prefetch"]).then(function (cache) {
cache.put(event.request, responseToCache);
});
return response;
});
})
);
// event.respondWith(
// // Opens Cache objects that start with 'font'.
// caches.open(CURRENT_CACHES["font"]).then(function (cache) {
// return cache
// .match(event.request)
// .then(function (response) {
// if (response) {
// console.log(" Found response in cache:", response);
// return response;
// }
// })
// .catch(function (error) {
// // Handles exceptions that arise from match() or fetch().
// console.error(" Error in fetch handler:", error);
// throw error;
// });
// })
// );
});