forked from fiatjaf/coisas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service-worker.js
79 lines (68 loc) · 2.35 KB
/
service-worker.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/* global caches, self, fetch */
const always = [
'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css',
'https://cdnjs.cloudflare.com/ajax/libs/notie/4.3.1/notie.min.css',
'https://cdnjs.cloudflare.com/ajax/libs/notie/4.3.0/notie.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.27.4/codemirror.min.css',
'https://cdn.rawgit.com/chenglou/react-treeview/6e9eacf4/react-treeview.css',
'https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.28.0/mode/css/css.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.28.0/mode/htmlmixed/htmlmixed.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.28.0/mode/javascript/javascript.js'
]
const currentCache = 'v1'
this.addEventListener('install', event => {
event.waitUntil(
caches.open(currentCache).then(cache => {
return cache.addAll(always)
})
)
})
this.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(keyList =>
Promise.all(keyList.map(key => {
if (key !== currentCache) {
return caches.delete(key)
}
}))
)
)
})
var currentRepo = ''
self.addEventListener('message', event => {
currentRepo = event.data.currentRepo
})
self.addEventListener('fetch', event => {
if (event.request.method !== 'GET') return
if (event.request.url.slice(0, 4) !== 'http') return
// the predefined urls we'll always serve them from the cache
if (always.indexOf(event.request.url) !== -1) {
event.respondWith(caches.match(event.request))
return
}
// for the image urls we'll try the current github repository
let networkURL = event.request.url.split('#')[0]
if (currentRepo &&
networkURL.match(location.host) &&
networkURL.match(/(png|jpe?g|gif|svg)$/)) {
let path = networkURL.split('/').slice(3).join('/')
event.respondWith(
fetch(
`https://raw.githubusercontent.com/${currentRepo}/master/${path}`
)
)
return
}
// try to fetch from the network
event.respondWith(
fetch(event.request)
.then(response => {
// save a clone of our response in the cache
let cacheCopy = response.clone()
caches.open(currentCache).then(cache => cache.put(event.request, cacheCopy))
return response
})
// if it fails we'll serve from the cache
.catch(caches.match(event.request))
)
})