-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathsw.js
More file actions
76 lines (70 loc) · 2.62 KB
/
Copy pathsw.js
File metadata and controls
76 lines (70 loc) · 2.62 KB
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
// You have to supply a name for your cache, this will
// allow us to remove an old one to avoid hitting disk
// space limits and displaying old resources
var cacheName = 'v1';
// Assesto catche
var assetsToCache = [
'/css/main.min.css',
'/js/scripts.js',
'/images/unicorncode.svg',
'/images/unicorn-single.svg',
'/fonts/icomoon.woff',
'https://fonts.gstatic.com/s/alegreyasanssc/v3/AjAmkoP1y0Vaad0UPPR46zqXxEMZsh1tOw6O6jsjRmU.woff2'
];
self.addEventListener('install', function(event) {
// waitUntil() ensures that the Service Worker will not
// install until the code inside has successfully occurred
event.waitUntil(
// Create cache with the name supplied above and
// return a promise for it
caches.open(cacheName).then(function(cache) {
// Important to `return` the promise here to have `skipWaiting()`
// fire after the cache has been updated.
return cache.addAll(assetsToCache);
}).then(function() {
// `skipWaiting()` forces the waiting ServiceWorker to become the
// active ServiceWorker, triggering the `onactivate` event.
// Together with `Clients.claim()` this allows a worker to take effect
// immediately in the client(s).
return self.skipWaiting();
})
);
});
// Activate event
// Be sure to call self.clients.claim()
self.addEventListener('activate', function(event) {
// `claim()` sets this worker as the active worker for all clients that
// match the workers scope and triggers an `oncontrollerchange` event for
// the clients.
return self.clients.claim();
});
self.addEventListener('fetch', function(event) {
// Get current path
var requestUrl = new URL(event.request.url);
// Save all resources on origin path only
if (requestUrl.origin === location.origin) {
if (requestUrl.pathname === '/') {
event.respondWith(
// Open the cache created when install
caches.open(cacheName).then(function(cache) {
// Go to the network to ask for that resource
return fetch(event.request).then(function(networkResponse) {
// Add a copy of the response to the cache (updating the old version)
cache.put(event.request, networkResponse.clone());
// Respond with it
return networkResponse;
}).catch(function() {
// If there is no internet connection, try to match the request
// to some of our cached resources
return cache.match(event.request);
})
})
);
}
}
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
});