forked from lorenseanstewart/nextjs-mdx-blog-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
my-worker.js
72 lines (62 loc) · 2.23 KB
/
my-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
// change precacheVersion whenever you update this file
// (e.g. if you add a new url to the precacheFiles array.)
const precacheVersion = 1;
const precacheName = "precache-v" + precacheVersion;
/*
In the array below, include the urls to all the posts/pages
that you want cached for offline access. For files that are nested
more than two directories deep, you may need the full url.
E.g. Pages within `/blog/animation/`, may not get cached. You may need
something like `/blog/animation/using-react-sprint` for each page in
the directory.
*/
const precacheFiles = ["/", "/blog/", "/static/"];
self.addEventListener("install", e => {
console.log("[ServiceWorker] Installed");
self.skipWaiting();
e.waitUntil(
caches.open(precacheName).then(cache => {
console.log("[ServiceWorker] Precaching files");
return cache.addAll(precacheFiles);
})
);
});
self.addEventListener("activate", e => {
console.log("[ServiceWorker] Activated");
e.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(thisCacheName => {
if (
thisCacheName.includes("precache") &&
thisCacheName !== precacheName
) {
console.log(
"[ServiceWorker] Removing cached files from old cache - ",
thisCacheName
);
return caches.delete(thisCacheName);
}
})
);
})
);
});
self.addEventListener("fetch", e => {
e.respondWith(
caches.match(e.request).then(cachedResponse => {
if (cachedResponse) {
console.log("Found in cache!");
return cachedResponse;
}
return fetch(e.request)
.then(fetchResponse => fetchResponse)
.catch(err => {
const isHTMLPage =
e.request.method == "GET" &&
e.request.headers.get("accept").includes("text/html");
if (isHTMLPage) return caches.match("/");
});
})
);
});