-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsw-template.js
59 lines (54 loc) · 1.58 KB
/
sw-template.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
var cachePrefix = 'touchwords';
var cacheVersion = 'v2';
var cacheName = `${cachePrefix}-${cacheVersion}`;
var BASE_FILE_PATH = './';
var filesToCache = [
BASE_FILE_PATH + 'favicon.ico',
BASE_FILE_PATH + 'index.html',
BASE_FILE_PATH + '404.html',
];
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(cacheName).then(function(cache) {
return cache.addAll(filesToCache);
}).catch(function(err) {
console.log(err);
}).then(function() {
return self.skipWaiting();
}));
});
self.addEventListener('fetch', function(event) {
console.log('Service Worker Fetch...');
event.respondWith(
caches.match(event.request)
.then(function(response) {
if(response){
console.log('Serve from cache', response);
return response;
}
return fetch(event.request)
.then(response =>
caches.open(cacheName.prefetch)
.then((cache) => {
// cache response after making a request
cache.put(event.request, response.clone());
// return original response
return response;
})
)
})
)
})
self.addEventListener('activate', function(event) {
console.log('sw activate');
event.waitUntil(
caches.keys().then(function(keyList) {
return Promise.all(keyList.map(function(key) {
if (key.startsWith(`{cachePrefix}`) && key !== cacheName) {
console.log('sw removing old cache', key);
return caches.delete(key);
}
}));
})
);
});