-
Notifications
You must be signed in to change notification settings - Fork 0
/
sw.js
84 lines (73 loc) · 2.24 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
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
/* eslint-env serviceworker */
var TRACKING_REGEX = /https?:\/\/((www|ssl)\.)?google-analytics\.com/
var IS_DEVELOPMENT = process.env.NODE_ENV === 'development'
var CACHE_KEY = getCacheKey()
var FILES = [
'/',
'/manifest.json'
].concat(process.env.ASSET_LIST).filter(Boolean)
self.addEventListener('install', function oninstall (event) {
event.waitUntil(
caches
.open(CACHE_KEY)
.then(cache => cache.addAll(FILES))
.then(() => self.skipWaiting())
)
})
self.addEventListener('activate', function onactivate (event) {
event.waitUntil(clear().then(() => self.clients.claim()))
})
self.addEventListener('fetch', function onfetch (event) {
var req = event.request
var url = new self.URL(req.url)
var isSameOrigin = self.location.origin === url.origin
var isHTML = req.headers.get('accept').includes('text/html')
event.respondWith(
caches.open(CACHE_KEY).then(function (cache) {
return cache.match(req).then(function (cached) {
// bypass cache for certain types
if ((isHTML && isSameOrigin) || IS_DEVELOPMENT) {
return update(cache, req, cached)
}
// bypass cache for tracking scripts
if (TRACKING_REGEX.test(url.href)) return self.fetch(req)
// use cached response
return cached || update(cache, req)
})
})
)
// fetch request and update cache
// (Cache, Request, Response?) -> Response|Promise
function update (cache, req, fallback) {
if (req.cache === 'only-if-cached' && req.mode !== 'same-origin') {
return fallback
}
return self.fetch(req).then(function (response) {
if (!response.ok) {
if (fallback) return fallback
} else {
let type = req.headers.get('Content-Type')
if (type && type.toUpperCase() === 'GET') {
cache.put(req, response.clone())
}
}
return response
})
}
})
// clear application cache
// () -> Promise
function clear () {
return caches.keys().then(function (keys) {
return Promise.all(keys.map((key) => caches.delete(key)))
})
}
// get application cache key
// () -> str
function getCacheKey () {
if (process.env.SOURCE_VERSION) {
return process.env.SOURCE_VERSION
} else {
return process.env.npm_package_version
}
}