-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice-worker.js
107 lines (76 loc) · 2.54 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
// Set a name for the current cache
var cacheName = 'v1';
// Default files to always cache
var cacheFiles = [
'./',
'./index.html',
'./js/app.js',
'./css/reset.css',
'./css/style.css',
'https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,700,400italic,700italic'
]
self.addEventListener('install', function(e) {
console.log('[ServiceWorker] Installed');
// e.waitUntil Delays the event until the Promise is resolved
e.waitUntil(
// Open the cache
caches.open(cacheName).then(function(cache) {
// Add all the default files to the cache
console.log('[ServiceWorker] Caching cacheFiles');
return cache.addAll(cacheFiles);
})
); // end e.waitUntil
});
self.addEventListener('activate', function(e) {
console.log('[ServiceWorker] Activated');
e.waitUntil(
// Get all the cache keys (cacheName)
caches.keys().then(function(cacheNames) {
return Promise.all(cacheNames.map(function(thisCacheName) {
// If a cached item is saved under a previous cacheName
if (thisCacheName !== cacheName) {
// Delete that cached file
console.log('[ServiceWorker] Removing Cached Files from Cache - ', thisCacheName);
return caches.delete(thisCacheName);
}
}));
})
); // end e.waitUntil
});
self.addEventListener('fetch', function(e) {
console.log('[ServiceWorker] Fetch', e.request.url);
// e.respondWidth Responds to the fetch event
e.respondWith(
// Check in cache for the request being made
caches.match(e.request)
.then(function(response) {
// If the request is in the cache
if ( response ) {
console.log("[ServiceWorker] Found in Cache", e.request.url, response);
// Return the cached version
return response;
}
// If the request is NOT in the cache, fetch and cache
var requestClone = e.request.clone();
fetch(requestClone)
.then(function(response) {
if ( !response ) {
console.log("[ServiceWorker] No response from fetch ")
return response;
}
var responseClone = response.clone();
// Open the cache
caches.open(cacheName).then(function(cache) {
// Put the fetched response in the cache
cache.put(e.request, responseClone);
console.log('[ServiceWorker] New Data Cached', e.request.url);
// Return the response
return response;
}); // end caches.open
})
.catch(function(err) {
console.log('[ServiceWorker] Error Fetching & Caching New Data', err);
});
}) // end caches.match(e.request)
); // end e.respondWith
});