-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsw.js
53 lines (42 loc) · 1.36 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
52
53
if (globalThis === globalThis.window) {
// main thread bootstrap
const src = document.currentScript.src;
const swc = navigator.serviceWorker;
const register = ()=> swc?.register(src);
const installable = ()=> swc.controller?.postMessage("clearCache");
const installed = ()=> swc.ready.then(r => r.active?.postMessage("loadCache"));
if (location.protocol === 'https:') {
register();
window.addEventListener("beforeinstallprompt", (e) => {
installable();
e.userChoice.then(uc => {
if (uc.outcome === 'accepted') installed();
});
})
}
} else {
// service worker thread
self.addEventListener("fetch", fetchHandler);
self.addEventListener("message", ({data}) => (
data === 'clearCache' ? clearCache():
data === 'loadCache' ? loadCache():
undefined
));
const cacheName = "osjs-app";
let cached = true;
function clearCache() {
cached = false;
caches.delete(cacheName);
}
function loadCache() {
cached = true;
fetch('manifest.json').then(response => response.json()).then(
files => caches.open(cacheName).then(c => c.addAll(files))
);
}
function fetchHandler(e) {
if (cached) e.respondWith(
caches.match(e.request).then(r => r || fetch(e.request))
);
}
}