-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsw.js
58 lines (54 loc) · 1.67 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
54
55
56
57
58
const cacheName = "quoted-cache-v0.2.1",
assets = [
"./",
"index.html",
"style.styl",
"script.js",
"img/quoted192.png",
"img/quoted512.png",
"https://fonts.googleapis.com/css?family=Quicksand",
"https://raw.githubusercontent.com/rohith/quoted/master/data/quotes.md"
]
self.addEventListener("install", event => {
event.waitUntil(
caches.open(cacheName).then(cache => cache.addAll(assets))
)
})
self.addEventListener("activate", event =>
event.waitUntil(
caches.keys().then(keys =>
Promise.all(keys.map(key => {
if (key !== cacheName) {
return caches.delete(key)
}
}))
)
)
)
self.addEventListener("fetch", event => {
let request = event.request
if (request.url === "https://raw.githubusercontent.com/rohith/quoted/master/data/quotes.md") {
event.respondWith(
caches.match(request)
.then(cacheResponse => {
let fetchResponse = fetchReq(request)
return cacheResponse || fetchResponse
})
)
} else {
event.respondWith(
caches.match(request).then(cacheResponse => cacheResponse || fetchReq(request))
)
}
})
function fetchReq(request) {
return fetch(request).then(netRes => {
let resClone = netRes.clone()
if (resClone.ok) {
caches.open(cacheName).then(cache => cache.put(request, resClone))
} else {
throw Error(response.statusText)
}
return netRes
})
}