-
Notifications
You must be signed in to change notification settings - Fork 0
/
service-worker.js
65 lines (61 loc) · 1.74 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
const cacheName = "v1.0.0";
const cacheAssets = [
"index.html",
"script.js",
"style.js",
"https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js",
"https://cdnjs.cloudflare.com/ajax/libs/html5-qrcode/2.3.8/html5-qrcode.min.js",
"https://cdnjs.cloudflare.com/ajax/libs/autosize.js/6.0.1/autosize.min.js",
"https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined",
];
// Call Install Event
self.addEventListener("install", (e) => {
console.log("Service Worker: Installed");
e.waitUntil(
caches
.open(cacheName)
.then((cache) => {
console.log("Service Worker: Caching Files");
cache.addAll(cacheAssets);
})
.then(() => self.skipWaiting()),
);
});
// Call Activate Event
self.addEventListener("activate", (e) => {
console.log("Service Worker: Activated");
// Remove unwanted caches
e.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cache) => {
if (cache !== cacheName) {
console.log("Service Worker: Clearing Old Cache");
return caches.delete(cache);
}
}),
);
}),
);
});
// Call Fetch Event
self.addEventListener("fetch", (e) => {
console.log("Service Worker: Fetching");
e.respondWith(
fetch(e.request)
.then((res) => {
// Make clone of response
const resClone = res.clone();
// Open cache
caches.open(cacheName).then((cache) => {
// Add response to cache
cache.put(e.request, resClone);
});
return res;
})
.catch(async (err) => {
console.error("Fetch failed; returning cached resource instead.", err);
return await caches.match(e.request);
}),
);
});