-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsw.js
36 lines (32 loc) · 1.03 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
const cacheName = "MuYuFocus"
function isResourceToCache(url) {
const resourcePattern = /\/assets\//
return resourcePattern.test(url)
}
// intercepting fetch operations
self.addEventListener("fetch", e => {
async function returnCachedResource(req) {
const cache = await caches.open(cacheName)
const cachedResponse = await cache.match(req.url)
if (cachedResponse) {
// return cached resources directly
return cachedResponse
}
let fetchResponse
try {
fetchResponse = await fetch(req)
} catch(err) {
return new Response("Network error happened: " + err, {
status: 408,
headers: { "Content-Type": "text/plain" },
})
}
if (isResourceToCache(req.url, "option")) {
// cache optional resources
cache.put(req.url, fetchResponse.clone())
}
return fetchResponse
}
const req = e.request
e.respondWith(returnCachedResource(req))
})