-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsw.js
73 lines (62 loc) · 2.07 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
const version = '20191230134902';
const cacheName = `static::${version}`;
const buildContentBlob = () => {
return ["/healthcare/dicom/2019/12/30/into-the-dicom-world-part-1.html","/about/","/categories/","/","/articles/tags/","/manifest.json","/assets/search.json","/assets/styles.css","/redirects.json","/feed.xml","/sitemap.xml","/robots.txt","", "/assets/default-offline-image.png", "/assets/scripts/fetch.js"
]
}
const updateStaticCache = () => {
return caches.open(cacheName).then(cache => {
return cache.addAll(buildContentBlob());
});
};
const clearOldCache = () => {
return caches.keys().then(keys => {
// Remove caches whose name is no longer valid.
return Promise.all(
keys
.filter(key => {
return key !== cacheName;
})
.map(key => {
console.log(`Service Worker: removing cache ${key}`);
return caches.delete(key);
})
);
});
};
self.addEventListener("install", event => {
event.waitUntil(
updateStaticCache().then(() => {
console.log(`Service Worker: cache updated to version: ${cacheName}`);
})
);
});
self.addEventListener("activate", event => {
event.waitUntil(clearOldCache());
});
self.addEventListener("fetch", event => {
let request = event.request;
let url = new URL(request.url);
// Only deal with requests from the same domain.
if (url.origin !== location.origin) {
return;
}
// Always fetch non-GET requests from the network.
if (request.method !== "GET") {
event.respondWith(fetch(request));
return;
}
// Default url returned if page isn't cached
let offlineAsset = "/offline/";
if (request.url.match(/\.(jpe?g|png|gif|svg)$/)) {
// If url requested is an image and isn't cached, return default offline image
offlineAsset = "/assets/default-offline-image.png";
}
// For all urls request image from network, then fallback to cache, then fallback to offline page
event.respondWith(
fetch(request).catch(async () => {
return (await caches.match(request)) || caches.match(offlineAsset);
})
);
return;
});