Skip to content

Commit

Permalink
Merge pull request #31 from Freakybob-Team/pwa-fix
Browse files Browse the repository at this point in the history
Add service worker i think
  • Loading branch information
wish13yt authored Jan 3, 2025
2 parents a679911 + c1b7a3f commit 6f6087d
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
5 changes: 5 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,11 @@ <h2>
</div>
</footer>
<script src="js/christmasmusic.js"></script>
<script>
if (typeof navigator.serviceWorker !== 'undefined') {
navigator.serviceWorker.register('js/pwabuilder-sw.js')
}
</script>
</body>
<script src="js/twemoji.js"></script>
</html>
Expand Down
54 changes: 54 additions & 0 deletions js/pwabuilder-sw.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// This is the service worker with the combined offline experience (Offline page + Offline copy of pages)

const CACHE = "pwabuilder-offline-page";

importScripts('https://storage.googleapis.com/workbox-cdn/releases/5.1.2/workbox-sw.js');

// TODO: replace the following with the correct offline fallback page i.e.: const offlineFallbackPage = "offline.html";
const offlineFallbackPage = "ToDo-replace-this-name.html";

self.addEventListener("message", (event) => {
if (event.data && event.data.type === "SKIP_WAITING") {
self.skipWaiting();
}
});

self.addEventListener('install', async (event) => {
event.waitUntil(
caches.open(CACHE)
.then((cache) => cache.add(offlineFallbackPage))
);
});

if (workbox.navigationPreload.isSupported()) {
workbox.navigationPreload.enable();
}

workbox.routing.registerRoute(
new RegExp('/*'),
new workbox.strategies.StaleWhileRevalidate({
cacheName: CACHE
})
);

self.addEventListener('fetch', (event) => {
if (event.request.mode === 'navigate') {
event.respondWith((async () => {
try {
const preloadResp = await event.preloadResponse;

if (preloadResp) {
return preloadResp;
}

const networkResp = await fetch(event.request);
return networkResp;
} catch (error) {

const cache = await caches.open(CACHE);
const cachedResp = await cache.match(offlineFallbackPage);
return cachedResp;
}
})());
}
});

0 comments on commit 6f6087d

Please sign in to comment.