-
-
Notifications
You must be signed in to change notification settings - Fork 531
Expand file tree
/
Copy pathsw.js
More file actions
88 lines (80 loc) · 2.19 KB
/
sw.js
File metadata and controls
88 lines (80 loc) · 2.19 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
const CACHE_NAME = 'sn-app-v1'
// keep in sync with webpack copy patterns in web.webpack.config.js
const APP_SHELL = [
'/',
'/index.html',
'/app.js',
'/app.css',
'/favicon/favicon.ico',
'/favicon/favicon-32x32.png',
'/favicon/apple-touch-icon.png',
'/manifest.webmanifest',
]
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
return cache.addAll(APP_SHELL)
})
)
// dont wait for old tabs to close
self.skipWaiting()
})
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((names) => {
return Promise.all(
names
.filter((name) => name !== CACHE_NAME)
.map((name) => caches.delete(name))
)
})
)
self.clients.claim()
})
self.addEventListener('fetch', (event) => {
const { request } = event
// let API calls and websocket stuff go straight to network
if (request.url.includes('/api/') || request.url.includes('/socket')) {
return
}
// navigation requests: network first, fall back to cached shell
if (request.mode === 'navigate') {
event.respondWith(
fetch(request)
.then((resp) => {
// stash a fresh copy if it's good
if (resp.ok) {
const clone = resp.clone()
caches.open(CACHE_NAME).then((cache) => cache.put(request, clone))
}
return resp
})
.catch(() => caches.match('/index.html'))
)
return
}
// everything else: cache first, then network
event.respondWith(
caches.match(request).then((cached) => {
if (cached) {
// refresh cache in bg
fetch(request)
.then((resp) => {
if (resp.ok) {
caches.open(CACHE_NAME).then((cache) => cache.put(request, resp))
}
})
.catch(() => {})
return cached
}
return fetch(request).then((resp) => {
// only cache same-origin stuff
if (resp.ok && new URL(request.url).origin === self.location.origin) {
const clone = resp.clone()
caches.open(CACHE_NAME).then((cache) => cache.put(request, clone))
}
return resp
})
})
)
})