diff options
author | João Augusto Costa Branco Marado Torres <torres.dev@disroot.org> | 2025-07-04 15:37:16 -0300 |
---|---|---|
committer | João Augusto Costa Branco Marado Torres <torres.dev@disroot.org> | 2025-07-04 15:37:16 -0300 |
commit | 2598c9ef0b945f13e94dba8f36c5fbb5cba58feb (patch) | |
tree | 39e1c481af223cb2356b994637aa4d1ded267934 /src | |
parent | 0fae4d0b001526a200b2ab1270cf353e4c3b5681 (diff) |
feat: offline support with service workers
Signed-off-by: João Augusto Costa Branco Marado Torres <torres.dev@disroot.org>
Diffstat (limited to 'src')
-rw-r--r-- | src/components/BaseHead.astro | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/src/components/BaseHead.astro b/src/components/BaseHead.astro index 912375e..41926ad 100644 --- a/src/components/BaseHead.astro +++ b/src/components/BaseHead.astro @@ -87,3 +87,49 @@ const { <meta property="twitter:image" content={image} /> <ClientRouter /> + +<script> + import { + Workbox, + type WorkboxLifecycleWaitingEvent, + } from "workbox-window"; + + if ("serviceWorker" in navigator) { + const wb = new Workbox("/sw.js", { type: "module" }); + + wb.addEventListener("activated", (_event) => { + const urlsToCache = [ + location.href, + ...performance.getEntriesByType("resource").map((r) => r.name), + ]; + wb.messageSW({ + type: "CACHE_URLS", + payload: { urlsToCache }, + }); + }); + + const showSkipWaitingPrompt = async ( + _event: WorkboxLifecycleWaitingEvent, + ) => { + wb.addEventListener("controlling", () => { + window.location.reload(); + }); + + const updateAccepted = await promptForUpdate(); + + if (updateAccepted) { + wb.messageSkipWaiting(); + } + }; + + wb.addEventListener("waiting", (event) => { + showSkipWaitingPrompt(event); + }); + + wb.register(); + } + + async function promptForUpdate(): Promise<boolean> { + return await Promise.resolve(confirm("update?")); + } +</script> |