-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice-worker.js
96 lines (83 loc) · 2.5 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
95
96
// Use a cacheName for cache versioning
const cacheName = "mockSpongebob-v1.2.7";
// Assets to be used for offline availability
const precachedAssets = [
// Image files
"./img/spongebob.jpg",
"./img/icon.png",
"./img/icon-144.png",
"./img/icon-192.png",
"./img/icon-512.png",
"./img/apple_app_icon.png",
"./img/webp/camera-icon.webp",
"./img/webp/camera-icon-active.webp",
"./img/webp/camera-trigger.webp",
"./img/webp/camera-flip.webp",
"./img/webp/microphoneOff.webp",
"./img/webp/microphoneOn.webp",
// Display files
"./css/styles.css",
"./index.html",
// JS files
"./js/controller.js",
"./js/sw-registrar.js",
"./js/camera.js",
"./js/math.js",
"./js/webSpeech.js",
"./js/mockTypes.js",
"./js/demonstration.js",
// MathJax
"https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js",
// Other
"./",
"./manifest.json",
];
// During the installation phase, you'll usually want to cache static assets.
self.addEventListener("install", (e) => {
self.skipWaiting(); // forces this service worker to become the active service worker.
// delete old cache, then precache updated assets.
const refreshCacheTask = caches
.keys()
.then((keys) => Promise.all(keys.map((key) => caches.delete(key))))
.then(() => caches.open(cacheName))
.then((cache) => cache.addAll(precachedAssets));
e.waitUntil(refreshCacheTask);
});
// Allow service worker to control current page on next load.
self.addEventListener("activate", (e) => {
console.log("Activating new service worker");
e.waitUntil(clients.claim());
});
/** Checks whether the current environment is for development. */
function isDevelopment() {
return location.hostname === "127.0.0.1" || location.hostname === "localhost";
}
if (!isDevelopment()) {
// Intercepts when the browser fetches a URL to check cache.
self.addEventListener("fetch", (e) => e.respondWith(cacheFirst(e.request)));
}
/**
* Returns a match from the cache first, only making a network request if necessary.
* @param {Request} req
*/
async function cacheFirst(req) {
const cache = await caches.open(cacheName);
const cached = await cache.match(req);
return cached ?? networkAndCache(cache, req);
}
/**
* Makes the network request immediately if possible,
* and saves the result in cache for future offline use.
* @param {Cache} cache
* @param {Request} req
*/
async function networkAndCache(cache, req) {
try {
const fresh = await fetch(req);
await cache.put(req, fresh.clone()); // must clone before use
return fresh;
} catch (e) {
console.error(e);
return;
}
}