-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathworker.js
81 lines (72 loc) · 1.85 KB
/
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
/* jshint esversion: 6 */
/* globals self, caches */
const currentCache = 'v4.6';
const assets = [
"/",
"/index.html",
"/styles/main.css",
"/styles/colors.css",
"/scripts/app.js",
"/scripts/clock.js",
"/scripts/calendar.js",
"/libs/suncalc/suncalc.js",
"/libs/astronomy/astronomy.browser.min.js"
];
// install event
self.addEventListener('install', event => {
console.log('Service worker install event', event);
// cache assets
event.waitUntil(
caches.open(currentCache)
.then(cache => {
console.log('Caching assets');
cache.addAll(assets);
})
);
});
// activate event
self.addEventListener('activate', event => {
console.log('Service worker activate event', event);
// delete old caches
event.waitUntil(
caches.keys()
.then(cacheNames => {
cacheNames.forEach(cacheName => {
if (cacheName !== currentCache) {
return caches.delete(cacheName);
}
});
})
);
});
// fetch event: cache first, then network
// see: https://developer.mozilla.org/en-US/docs/Web/API/Cache#examples
self.addEventListener('fetch', (event) => {
console.log(`Fetching: ${event.request.url}`);
event.respondWith(
caches.open(currentCache)
.then(cache => {
return cache
.match(event.request)
.then(response => {
if (response) {
console.log(`Getting from cache: ${response.url}`);
return response;
}
return fetch(event.request.clone()).then((response) => {
if (response.status < 400) {
console.log(`Response: ${response.status} ${response.statusText}, Caching: ${response.url}`);
cache.put(event.request, response.clone());
} else {
console.log(`Response: ${response.status} ${response.statusText}, Not caching: ${event.request.url}`);
}
return response;
});
})
.catch((error) => {
console.error("Error fetching:", error);
throw error;
});
})
);
});