-
Notifications
You must be signed in to change notification settings - Fork 0
/
sw.js
51 lines (43 loc) · 1.1 KB
/
sw.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
const cacheName = self.location.pathname
const pages = [
];
self.addEventListener("install", function (event) {
self.skipWaiting();
caches.open(cacheName).then((cache) => {
return cache.addAll(pages);
});
});
self.addEventListener("fetch", (event) => {
const request = event.request;
if (request.method !== "GET") {
return;
}
/**
* @param {Response} response
* @returns {Promise<Response>}
*/
function saveToCache(response) {
if (cacheable(response)) {
return caches
.open(cacheName)
.then((cache) => cache.put(request, response.clone()))
.then(() => response);
} else {
return response;
}
}
/**
* @param {Error} error
*/
function serveFromCache(error) {
return caches.open(cacheName).then((cache) => cache.match(request.url));
}
/**
* @param {Response} response
* @returns {Boolean}
*/
function cacheable(response) {
return response.type === "basic" && response.ok && !response.headers.has("Content-Disposition")
}
event.respondWith(fetch(request).then(saveToCache).catch(serveFromCache));
});