-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathsw.js
81 lines (71 loc) · 2.18 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
const version = 'v1.40::';
const staticCacheName = `${version}static`;
const pagesCacheName = `${version}pages`;
const offlinePages = [
'/',
];
function updateStaticCache() {
return caches.open(staticCacheName).then((cache) => {
return cache.addAll([
'/',
'/_include/js/main.min.js',
'/_include/css/main.min.css',
'/offline.html',
'/404.html',
]);
});
}
function stashInCache(cacheName, request, response) {
caches.open(cacheName).then(cache => cache.put(request, response));
}
// Remove caches whose name is no longer valid
function clearOldCaches() {
return caches.keys().then((keys) => {
return Promise.all(keys
.filter(key => key.indexOf(version) !== 0)
.map(key => caches.delete(key)),
);
});
}
self.addEventListener('install', (event) => {
event.waitUntil(updateStaticCache().then(() => self.skipWaiting()));
});
self.addEventListener('activate', (event) => {
event.waitUntil(clearOldCaches().then(() => self.clients.claim()));
});
self.addEventListener('fetch', (event) => {
let request = event.request;
let url = new URL(request.url);
// Ignore non-GET requests
if (request.method !== 'GET') {
return;
}
// For HTML requests, try the network first, fall back to the cache, finally the offline page
if (request.headers.get('Accept').indexOf('text/html') !== -1) {
event.respondWith(fetch(request).then((response) => {
// NETWORK
// Stash a copy of this page in the pages cache
let copy = response.clone();
if (offlinePages.includes(url.pathname) || offlinePages.includes(url.pathname + '/')) {
stashInCache(staticCacheName, request, copy);
} else {
stashInCache(pagesCacheName, request, copy);
}
return response;
}).catch(() => {
// CACHE or FALLBACK
return caches.match(request).then(response => response || caches.match('/offline.html'));
}),
);
return;
}
// For non-HTML requests, look in the cache first, fall back to the network
event.respondWith(caches.match(request).then(response => {
// CACHE
return response || fetch(request).then(response => {
// NETWORK
return response;
});
}),
);
});