-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
service-worker.js
executable file
·100 lines (85 loc) · 2.62 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
---
layout: compress
permalink: /service-worker.js
---
const OFFLINE = 'runtime';
const PRECACHE = 'precache-v{{ site.time | date: "%Y%m%d%H%M" }}';
const RUNTIME = 'runtime';
const OFFLINE_URL = 'offline.html';
const PRECACHE_URLS = [
'index.html',
'./',
'./?source=pwa',
'assets/css/pre-commit-dependency.css',
'assets/js/pre-commit-dependency.js'
];
self.addEventListener('install', event => {
event.waitUntil((async () => {
const offlineCache = await caches.open(OFFLINE);
await offlineCache.add(new Request(OFFLINE_URL, {cache: 'reload'}));
caches.open(PRECACHE)
.then(cache => cache.addAll(PRECACHE_URLS))
.then(self.skipWaiting());
})());
});
self.addEventListener('activate', event => {
const currentCaches = [PRECACHE, RUNTIME, OFFLINE];
event.waitUntil(
caches.keys().then(cacheNames => {
return cacheNames.filter(cacheName => !currentCaches.includes(cacheName));
}).then(cachesToDelete => {
return Promise.all(cachesToDelete.map(cacheToDelete => {
return caches.delete(cacheToDelete);
}));
}).then(() => self.clients.claim())
);
});
self.addEventListener('fetch', event => {
let tryInCachesFirst = caches.open(PRECACHE).then(cache => {
return cache.match(event.request).then(response => {
if (!response) {
return handleNoCacheMatch(event);
}
/* Update cache record in the background. */
fetchFromNetworkAndCache(event);
/* Reply with stale data. */
return response
});
});
event.respondWith(tryInCachesFirst);
});
/**
* Fetch from network and cache.
*
* @param event
* @returns {Promise<* | void>}
*/
let fetchFromNetworkAndCache = (event) => {
/* DevTools will trigger these o-i-c requests, which this can't handle. */
if (event.request.cache === 'only-if-cached'
&& event.request.mode !== 'same-origin'
) {
return;
}
return fetch(event.request).then(result => {
/* Foreign requests may be res.type === 'opaque' and missing a url. */
if (!result.url) return result;
/* Regardless, we don't want to cache other origins' assets. */
if (new URL(result.url).origin !== location.origin) return result;
return caches.open(PRECACHE).then(cache => {
if (event.request.method && event.request.method === 'GET') {
cache.put(event.request, result.clone());
}
return result;
});
}).catch(err => console.error(event.request.url, err));
};
/**
* Circular call for non-match, in case we want to do something different.
*
* @param event
* @returns {Promise<*|void>}
*/
let handleNoCacheMatch = (event) => {
return fetchFromNetworkAndCache(event);
};