-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsw.js
More file actions
52 lines (37 loc) · 1.07 KB
/
Copy pathsw.js
File metadata and controls
52 lines (37 loc) · 1.07 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
const CONTENTS = [
".",
"index.css",
"index.js"
];
// sw.js
const cache_name = "PWA_Cache"; // The string used to identify our cache
self.addEventListener("install", event => {
event.waitUntil(
caches
.open(cache_name)
.then(cache => {
return cache.addAll(CONTENTS);
})
.catch(err => console.log(err))
);
});
//Fetch first, and cache in fallback
async function getFromNetworkOrCache(request) {
let response = null;
try {
response = await fetch(request);
} catch {
return caches.match(request)
}
const cache = await caches.open(cache_name);
cache.put(request, response.clone());
return response;
}
self.addEventListener('fetch', function(event) {
let req = event.request;
// If fetch is a navigation, answer with the "." ressource instead, to simulate serving a PWA
if (req.mode === "navigate") {
req = new Request(new URL(".", this.serviceWorker.scriptURL));
}
event.respondWith(getFromNetworkOrCache(req))
});