-
Notifications
You must be signed in to change notification settings - Fork 0
/
service-worker.js
94 lines (70 loc) · 2.54 KB
/
service-worker.js
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
var cacheName = 'pizza-zine';
/* Start the service worker and cache all of the app's content or use the existing one */
self.addEventListener('install', function (e) {
console.log('Service worker installed.');
self.skipWaiting();
});
self.addEventListener('activate', function (e) {
return self.clients.claim();
});
/**
* True if the service worker should add the request to a persistent cache.
*/
let addToCache = false;
/**
* Serves the cached version of the request if it exists, otherwise fetches the
* request from the network and caches it. Fetch is used in the default mode,
* which will use the cache for most network requests, freshening the cache
* as required.
*/
async function fetchAndCache(request) {
const cache = await caches.open(cacheName);
const cachedResponse = await cache.match(request);
try {
if (request.url.endsWith("?cached")) {
request = new Request(request.url.replace("?cached", "?uncached"), request);
let rv = await cache.match(request);
if (rv == null) {
rv = new Response("Not found in cache.", { status: 404, statusText: "Not found in cache." });
}
return rv;
}
let headers = { }
if (cachedResponse) {
if (cachedResponse.headers.get('Last-Modified')) {
headers['If-Modified-Since'] = cachedResponse.headers.get('Last-Modified');
}
if (cachedResponse.headers.get('ETag')) {
headers['If-None-Match'] = cachedResponse.headers.get('ETag');
}
}
const response = await fetch(request, { headers: headers });
if (cachedResponse && response.status == 304) {
return cachedResponse;
}
if (addToCache && response.status == 200) {
await cache.put(request, response.clone());
}
return response;
} catch (e) {
if (cachedResponse) {
console.log('Served from cache: ' + request.url);
return cachedResponse;
}
console.log('Not found in cache: ' + request.url);
throw e;
}
}
/* Serve cached content when offline */
self.addEventListener('fetch', function (e) {
e.respondWith(fetchAndCache(e.request));
});
self.addEventListener('message', function (e) {
if (e.data[0] == "clearCache") {
caches.delete(cacheName);
console.log("Cache cleared in service worker.");
addToCache = false;
} else if (e.data[0] == "loadCache") {
addToCache = true;
}
});