-
Notifications
You must be signed in to change notification settings - Fork 6
/
sw.js
37 lines (25 loc) · 1.06 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
const MAIN_CACHE = 'main';
self.addEventListener("install", async (event) => {
event.waitUntil((async () => {
const cacheKeys = await caches.keys()
await Promise.all(cacheKeys.map(name => caches.delete(name)))
const cache = await caches.open(MAIN_CACHE)
await cache.addAll(['.'])
})())
});
const cacheFirst = (event) => {
if (event.request.method.toLowerCase() != 'get') return
if (event.request.headers.get('Range') != null) return
const requestUrl = new URL(event.request.url)
if (requestUrl.protocol != 'http:' && requestUrl.protocol != 'https:') return;
event.respondWith((async ()=>{
const cache = await caches.open(MAIN_CACHE)
const responsePromise = fetch(event.request).then((response) => {
if (response.ok) cache.put(event.request, response.clone())
return response
})
let cacheResponse = await caches.match(event.request)
return cacheResponse || await responsePromise
})())
};
self.addEventListener('fetch', cacheFirst);