Skip to content

Commit 2c148ab

Browse files
authored
Create pwabuilder-sw.js
1 parent b76513f commit 2c148ab

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

pwabuilder-sw.js

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// This is the "Offline page" service worker
2+
3+
importScripts('https://storage.googleapis.com/workbox-cdn/releases/5.0.0/workbox-sw.js');
4+
5+
const CACHE = "pwabuilder-page";
6+
7+
// TODO: replace the following with the correct offline fallback page i.e.: const offlineFallbackPage = "offline.html";
8+
const offlineFallbackPage = "ToDo-replace-this-name.html";
9+
10+
self.addEventListener("message", (event) => {
11+
if (event.data && event.data.type === "SKIP_WAITING") {
12+
self.skipWaiting();
13+
}
14+
});
15+
16+
self.addEventListener('install', async (event) => {
17+
event.waitUntil(
18+
caches.open(CACHE)
19+
.then((cache) => cache.add(offlineFallbackPage))
20+
);
21+
});
22+
23+
if (workbox.navigationPreload.isSupported()) {
24+
workbox.navigationPreload.enable();
25+
}
26+
27+
self.addEventListener('fetch', (event) => {
28+
if (event.request.mode === 'navigate') {
29+
event.respondWith((async () => {
30+
try {
31+
const preloadResp = await event.preloadResponse;
32+
33+
if (preloadResp) {
34+
return preloadResp;
35+
}
36+
37+
const networkResp = await fetch(event.request);
38+
return networkResp;
39+
} catch (error) {
40+
41+
const cache = await caches.open(CACHE);
42+
const cachedResp = await cache.match(offlineFallbackPage);
43+
return cachedResp;
44+
}
45+
})());
46+
}
47+
});

0 commit comments

Comments
 (0)