-
Notifications
You must be signed in to change notification settings - Fork 0
/
swCopy
76 lines (55 loc) · 1.94 KB
/
swCopy
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
self.addEventListener("activate", function(evt) {
console.log("[ServiceWorker] Activated")
evt.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(cacheNames.map(function(thisCacheName) {
if (thisCacheName !== cacheName) {
console.log("[ServiceWorker] Removing cached files from", thisCacheName);
return caches.delete(thisCacheName);
}
}))
})
)
})
self.addEventListener("fetch", function(evt) {
console.log("[ServiceWorker] Fetching", evt.request.url);
if (!(evt.request.url.indexOf('http') === 0)) {
return;
}
evt.respondWith(
caches.match(evt.request).then(function(response) {
if (response) {
console.log("[ServiceWorker] Found in cache", evt.request.url);
return response;
}
var requestClone = evt.request.clone();
fetch(requestClone)
.then(function(response) {
if (!response) {
console.log("[ServicerWorker] No response from fetch")
return response;
}
})
var responseClone = response.clone();
caches.open(cacheName).then(function(cache) {
cache.put(e.request, responseClone);
limitCacheSize(cacheName, 100);
return response;
})
})
.catch(function(err) {
console.log("[ServiceWorker] Error Fetching & Caching new version.")
caches.match("/fallback")
})
)
})
//cache size limit function
const limitCacheSize = (name, size) => {
caches.open(name).then(cache => {
cache.keys().then(keys => {
if (keys.length > size) {
cache.delete(keys[0]).then(limitCacheSize(name, size));
}
})
})
}