-
Notifications
You must be signed in to change notification settings - Fork 33
/
sw.js
74 lines (65 loc) · 1.84 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
---
---
var CACHE_NAME = '{{site.time}}';
var urlsToCache = [
'/',
'/assets/img/avatar.jpg',
'/assets/css/site.css',
'/assets/js/blog.min.js'
];
var blackList = [
/google-analytics.com.*collect/,
/^chrome-extension:\/\//
];
self.addEventListener('install', function (event) {
event.waitUntil(caches.open(CACHE_NAME).then(function (cache) {
return cache.addAll(urlsToCache);
}));
});
self.addEventListener('activate', function (event) {
event.waitUntil(caches.keys().then(function (cacheNames) {
return Promise.all(cacheNames.map(function (cacheName) {
if (cacheName !== CACHE_NAME) {
return caches.delete(cacheName);
}
}));
}));
});
self.addEventListener('fetch', function (event) {
if (
event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin'
) return cache(event.request);
if (
event.request.method !== 'GET' ||
blackList.some(function (regex) {
return regex.exec(event.request.url);
})
) return network(event.request);
var pn = networkAndSave(event.request);
event.respondWith(cache(event.request).then(function (res) {
return res || pn;
}).catch(function () {
return pn;
}));
});
function cache (req) {
return caches.open(CACHE_NAME).then(cache => cache.match(req.clone()));
}
function networkAndSave (req) {
return network(req).then(function (res) {
if (validate(res)) save(req.clone(), res.clone());
return res;
});
}
function network (req) {
return fetch(req.clone());
}
function save (key, val) {
return caches.open(CACHE_NAME).then(function (cache) {
cache.put(key, val);
});
}
function validate (res) {
if (res && res.type === 'basic' && res.status !== 200) return false;
return true;
}