-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsw.js
57 lines (53 loc) · 1.47 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
// Define the Caches
var staticCacheName = 'SW_v.';
// Set Get Random number for Cache ID
var randomNumberBetween0and19999 = Math.floor(Math.random() * 20000);
var cache_id = randomNumberBetween0and19999;
staticCacheName += cache_id;
self.addEventListener('install', () =>
console.log('SW installed'));
// Call Activate Event
self.addEventListener('activate', (e) => {
console.log('SW activated');
// Remove unwanted cashes
e.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cache => {
if (cache !== staticCacheName) {
console.log('SW Clearing old cashe');
return caches.delete(cache)
}
})
)
})
)
});
self.addEventListener('fetch',
function(event)
{
event.respondWith
(
caches.match(event.request).then(
function(response) {
if (response !== undefined) return response;
else {
return fetch(event.request).then(
function (response)
{
let responseClone = response.clone();
caches.open(staticCacheName).then(
function(cache)
{
cache.put(event.request, responseClone);
}
);
return response;
}
);
}
}
) // end of promise for cache match
); // end of respond with
}
);