forked from eddiesigner/liebling
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathservice-worker.js
More file actions
81 lines (74 loc) · 2.16 KB
/
Copy pathservice-worker.js
File metadata and controls
81 lines (74 loc) · 2.16 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
77
78
79
80
81
const CACHE_NAME = 'contentCache';
const offlineUrl = '/offline/';
const adminPageSlug = '/ghost';
const toCache = [
'/assets/css/offline.css',
'/pwa/status.js',
offlineUrl
];
/**
* The event listener for the service worker installation and cache the offline page.
*/
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => cache.addAll(toCache))
.then(self.skipWaiting())
);
});
/**
* Is the current request for an HTML page?
* @param {Object} event
*/
function isHtmlPage(event) {
return event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html');
}
/**
* Fetch and cache any results as we receive them.
*/
self.addEventListener('fetch', event => {
if (!event.request.url.includes("/ghost/")) {
event.respondWith(
caches.match(event.request)
.then(response => {
// Only return cache if it's not an HTML page
if (response && !isHtmlPage(event)) {
return response;
}
return fetch(event.request).then(
function (response) {
// Dont cache if not a 200 response
if (!response || response.status !== 200) {
return response;
}
let responseToCache = response.clone();
caches.open(CACHE_NAME)
.then(function (cache) {
cache.put(event.request, responseToCache);
});
return response;
}
).catch(error => {
// Check if the user is offline first and is trying to navigate to a web page. If so serve offline page.
if (isHtmlPage(event)) {
return caches.match(offlineUrl);
}
});
})
);
}
});
self.addEventListener('activate', function (event) {
event.waitUntil(
caches.keys()
.then((keyList) => {
return Promise.all(keyList.map((key) => {
if (key !== CACHE_NAME) {
console.log('[ServiceWorker] Removing old cache', key)
return caches.delete(key)
}
}))
})
.then(() => self.clients.claim())
)
})