forked from richtr/devopera
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service-worker.js
74 lines (68 loc) · 1.84 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
'use strict';
const PREFIX = 'devopera';
const HASH = ''; // Calculated when running `grunt`.
const OFFLINE_CACHE = `${PREFIX}-${HASH}`;
const OFFLINE_URL = '/errors/offline.html';
importScripts('/scripts/sw-cache-polyfill.js');
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(OFFLINE_CACHE).then(function(cache) {
return cache.addAll([
OFFLINE_URL,
'/styles/screen.css',
'/images/github.svg',
'/images/logo.svg',
'/scripts/highlight.js',
'/scripts/salvattore.js'
]);
})
);
});
self.addEventListener('activate', function(event) {
// Delete old asset caches.
event.waitUntil(
caches.keys().then(function(keys) {
return Promise.all(
keys.map(function(key) {
if (
key != OFFLINE_CACHE &&
key.startsWith(`${PREFIX}-`) &&
!key.startsWith(`${PREFIX}-article-`)
) {
return caches.delete(key);
}
})
);
})
);
});
self.addEventListener('fetch', function(event) {
if (
event.request.method == 'GET' &&
event.request.headers.get('accept').includes('text/html')
) {
// It’s a GET request for an HTML document.
//console.log('Handling fetch event for', event.request.url);
event.respondWith(
fetch(event.request).catch(function(exception) {
// The `catch` is only triggered if `fetch()` throws an exception,
// which most likely happens due to the server being unreachable.
console.error(
'Fetch failed; returning offline page instead.',
exception
);
return caches.open(OFFLINE_CACHE).then(function(cache) {
return cache.match(OFFLINE_URL);
});
})
);
} else {
// It’s not a request for an HTML document, but rather for a CSS or SVG
// file or whatever…
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
}
});