-
-
Notifications
You must be signed in to change notification settings - Fork 72
/
sw.js
67 lines (58 loc) · 1.54 KB
/
sw.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
---
layout: null
---
var CACHE = 'cache-and-update';
var urlsToCache = [
{% for page in site.pages %}
{% if page.url contains 'projects' or page.url contains '404' %}
{% else %}
'{{ page.url }}',
{% endif %}
{% endfor %}
{% for post in site.posts %}
'{{ post.url }}',
{% endfor %}
{% for file in site.static_files %}
'{{ file.path }}',
{% endfor %}
];
self.addEventListener('install', function(evt) {
evt.waitUntil(caches.open(CACHE).then(function(cache) {
cache.addAll(urlsToCache);
}));
});
self.addEventListener('fetch', function(evt) {
evt.respondWith(fromCache(evt.request));
evt.waitUntil(update(evt.request));
});
function fromCache(request) {
return caches.open(CACHE).then(function(cache) {
return cache.match(request).then(function(response) {
if (response != undefined) {
return response;
} else {
return fetchFromInternet(request);
}
});
}).catch(function() {
return caches.match('/offline.html');
});
}
function update(request) {
return caches.open(CACHE).then(function(cache) {
return fetchFromInternet(request);
});
}
function fetchFromInternet(request) {
var fetchRequset = request.clone();
return fetch(fetchRequset).then(function(response) {
if (!response || response.status !== 200 || response.type !== 'basic') {
return response;
}
var responseToCache = response.clone();
caches.open(CACHE).then(function(cache) {
cache.put(request, responseToCache);
});
return response;
});
}