-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathsw.js
89 lines (75 loc) · 2.53 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
---
layout: null
---
const urls = [];
// Cache assets
{% for asset in site.static_files -%}
{%- if asset.path contains '/assets/fonts' or asset.path contains '/assets/icons' or asset.path contains '/assets/img' or asset.path contains '/assets/favicons' or asset.extname == '.js' -%}
urls.push("{{ asset.path | relative_url }}");
{%- endif -%}
{%- endfor %}
// Cache posts
{% for post in site.posts limit: 10 -%}
urls.push("{{ post.url | relative_url }}");
{%- endfor %}
// Cache pages
{% for page in site.html_pages -%}
{%- unless page.path contains 'blog/archive' -%}
urls.push("{{ page.url | relative_url }}");
{%- endunless -%}
{%- endfor %}
// Cache name: adjust version number to invalidate service worker cache.
const CACHE_NAME = 'fragariacz-cache-v{{ site.service_worker.cache_version }}';
function precache() {
caches.open(CACHE_NAME).then(function(cache) {
console.log(`[sw] Opened cache ${CACHE_NAME}`);
return cache.addAll(urls);
});
}
function storeInCache(request, response) {
caches.open(CACHE_NAME).then(cache => {
cache.put(request, response);
});
}
function loadFromNetwork(request, timeout) {
return new Promise((fulfill, reject) => {
let tid = setTimeout(reject, timeout);
fetch(request).then(response => {
clearTimeout(tid);
const responseClone = response.clone();
fulfill(response);
storeInCache(request, responseClone);
}, reject);
});
}
function loadFromCache(request) {
return caches.open(CACHE_NAME).then(cache => {
return cache.match(request).then(matching => {
return matching || Promise.reject('no-match');
});
});
}
self.addEventListener('install', function(event) {
console.log(`[sw] Installing ...`);
// Make sure to not stuck waiting for current sw to become terminated.
self.skipWaiting();
// Perform install steps
event.waitUntil(precache());
});
self.addEventListener('fetch', event => {
const request = event.request;
let handler = null;
if (request.method === 'GET') {
handler = loadFromNetwork(request, 1500)
.catch(err => loadFromCache(request))
.catch(err => {
console.warn('[sw] Could not load, redirecting to offline page ', err);
return caches.open(CACHE_NAME).then(cache => {
return cache.match('{{ "/offline/" | relative_url }}');
})
});
} else {
handler = fetch(request);
}
return event.respondWith(handler);
});