-
Notifications
You must be signed in to change notification settings - Fork 0
/
service-worker.js
75 lines (60 loc) · 2.46 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
(function() {
'use strict';
var version = 3;
var staticCacheName = 'pwa-demo-v' + version;
var filesToCache = [
'.',
'styles/style.css',
'images/favicon.ico',
'images/offline.svg' // An offline replacement for the remote image.
];
self.addEventListener('install', function(event) {
console.log('Installing new service worker...');
self.skipWaiting();
event.waitUntil(
caches.open(staticCacheName).then(function(cache) {
return cache.addAll(filesToCache);
})
);
});
self.addEventListener('activate', function(event) {
console.log('Activating new service worker...');
var cacheWhitelist = [staticCacheName];
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.map(function(cacheName) {
if (cacheWhitelist.indexOf(cacheName) === -1) {
return caches.delete(cacheName);
}
})
);
})
);
});
self.addEventListener('fetch', function(event) {
console.log('Fetching the url: ', event.request.url);
event.respondWith(
// Use ignoreSearch:true to ignore query string while matching urls
// because we utilize ?utm_source=app_manifest in the app manifest.
caches.match(event.request, {ignoreSearch:true}).then(function(response) {
if (response) {
console.log('Found ', event.request.url, ' in cache.');
return response;
}
console.log('Trying to get ', event.request.url, ' from network.');
if (event.request.url.indexOf('www.drupal.org') > -1) {
// Remove etag header to guarantee downloading the resource.
var headers = new Headers(event.request.headers);
headers.delete('etag');
// Try to obtain image from network.
return fetch(event.request).catch(function (reason) {
console.log('Replaced ', event.request.url, ' with the offline image from cache.');
return caches.match('images/offline.svg');
});
}
return fetch(event.request);
})
);
});
})();