-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathserviceworker.js
More file actions
61 lines (56 loc) · 1.59 KB
/
serviceworker.js
File metadata and controls
61 lines (56 loc) · 1.59 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
const CACHE = "bitrequest-page-v0.307",
offlineFallbackPage = "index.html";
// Install: cache core assets with new version
self.addEventListener("install", function(event) {
event.waitUntil(
caches.open(CACHE).then(function(cache) {
return cache.add(offlineFallbackPage);
})
);
self.skipWaiting(); // activate immediately
});
// Activate: delete old versioned caches
self.addEventListener("activate", function(event) {
event.waitUntil(
caches.keys().then(function(keys) {
return Promise.all(
keys.filter(function(key) {
return key.startsWith("bitrequest-page-") && key !== CACHE;
}).map(function(key) {
return caches.delete(key);
})
);
})
);
self.clients.claim(); // take control of open tabs
});
// Fetch: try network first, fall back to cache for offline
self.addEventListener("fetch", function(event) {
if (event.request.method !== "GET") return;
if (event.request.destination === "image") {
event.respondWith(
caches.open(CACHE).then(function(cache) {
return cache.match(event.request).then(function(cachedResponse) {
if (cachedResponse) {
return cachedResponse;
}
return fetch(event.request).then(function(networkResponse) {
cache.put(event.request, networkResponse.clone());
return networkResponse;
});
});
})
);
return;
}
event.respondWith(
fetch(event.request).catch(function(error) {
if (event.request.destination !== "document" || event.request.mode !== "navigate") {
return;
}
return caches.open(CACHE).then(function(cache) {
return cache.match(offlineFallbackPage);
});
})
);
});