Repository navigation
Expand file tree
/
Copy pathsw.js
More file actions
92 lines (84 loc) · 2.68 KB
/
Copy pathsw.js
File metadata and controls
92 lines (84 loc) · 2.68 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
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
const VERSION = 'luaslice-wiki-v3';
const CORE = [
'./',
'index.html',
'style.css',
'app.js',
'content.js',
'generator.js',
'playground.js',
'lua-runtime.js',
'vendor/fengari-web.js',
'vendor/marked.min.js',
'vendor/highlight.min.js',
'icons/logo.webp',
'manifest.webmanifest',
'icons/icon-192.png',
'icons/icon-512.png',
'icons/maskable-192.png',
'icons/maskable-512.png',
'icons/apple-touch-icon.png',
'icons/favicon-64.png'
];
const OPTIONAL = [
'logo.png',
'fonts/vcr.ttf',
'fonts/vcr-bold.ttf',
'cursor/cursor-default.png',
'cursor/cursor-pointer.png'
];
self.addEventListener('install', (event) => {
event.waitUntil((async () => {
const cache = await caches.open(VERSION);
await cache.addAll(CORE.map((u) => new Request(u, { cache: 'reload' })));
await Promise.all(OPTIONAL.map(async (u) => {
try {
const res = await fetch(new Request(u, { cache: 'reload' }));
if (res.ok) await cache.put(u, res);
} catch (e) {}
}));
})());
});
self.addEventListener('activate', (event) => {
event.waitUntil((async () => {
const keys = await caches.keys();
await Promise.all(keys.filter((k) => k.startsWith('luaslice-wiki-') && k !== VERSION).map((k) => caches.delete(k)));
if (self.registration.navigationPreload) await self.registration.navigationPreload.enable();
await self.clients.claim();
})());
});
self.addEventListener('message', (event) => {
if (event.data === 'skipWaiting') self.skipWaiting();
});
async function networkFirst(request, fallbackKey, preload) {
const cache = await caches.open(VERSION);
try {
const res = (preload && await preload) || await fetch(request);
if (res.ok) cache.put(fallbackKey || request, res.clone());
return res;
} catch (e) {
const hit = await cache.match(fallbackKey || request, { ignoreSearch: true });
if (hit) return hit;
throw e;
}
}
async function cacheFirst(request) {
const cache = await caches.open(VERSION);
const hit = await cache.match(request, { ignoreSearch: true });
if (hit) return hit;
const res = await fetch(request);
if (res.ok) cache.put(request, res.clone());
return res;
}
self.addEventListener('fetch', (event) => {
const req = event.request;
if (req.method !== 'GET') return;
const url = new URL(req.url);
if (req.mode === 'navigate') {
event.respondWith(networkFirst(req, 'index.html', event.preloadResponse).catch(() => caches.match('index.html')));
return;
}
if (url.origin !== location.origin) return;
const asset = /\.(png|jpe?g|gif|svg|webp|ico|ttf|otf|woff2?)$/i.test(url.pathname) || url.pathname.includes('/vendor/');
event.respondWith(asset ? cacheFirst(req) : networkFirst(req));
});