-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathenableServiceWorker.ts
More file actions
35 lines (32 loc) · 1.07 KB
/
enableServiceWorker.ts
File metadata and controls
35 lines (32 loc) · 1.07 KB
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
import { type QueryClient } from "@tanstack/react-query"
import { SW_CACHE_KEY } from "@repo/client/sw/useServiceWorker"
async function loadServiceWorker(client?: QueryClient, id?: string) {
try {
if (!("serviceWorker" in navigator)) return
console.debug("[SW] registering...")
const path = id ? `/sw.js?id=${id}` : "/sw.js"
const registration = await navigator.serviceWorker.register(path, {
scope: "/",
type: "module",
updateViaCache: "none",
})
await registration.update()
if (registration.active) {
console.debug("[SW] registered.")
client?.setQueryData(SW_CACHE_KEY, registration.active)
} else {
console.warn("[SW] registration never became active.")
}
} catch (e) {
console.error("[SW] registration failed: ", e)
}
}
export function enableServiceWorker(client?: QueryClient) {
window.addEventListener("load", () => loadServiceWorker(client), { once: true })
if (import.meta.hot) {
import.meta.hot.on("sw-rebuild", (data: { id: string }) => {
console.debug("[SW] Hot Module Reloading...")
loadServiceWorker(client, data.id)
})
}
}