Skip to content

Commit

Permalink
fix: service worker installation and activation handling triggers reload
Browse files Browse the repository at this point in the history
  • Loading branch information
Sheraff committed Oct 4, 2024
1 parent 46d0dd0 commit 5034258
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 5 deletions.
3 changes: 1 addition & 2 deletions public/sw.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,13 @@

const s = /** @type {ServiceWorkerGlobalScope} */(/** @type {unknown} */(self))

s.addEventListener("install", () => s.skipWaiting())
s.addEventListener("install", (event) => event.waitUntil(s.skipWaiting()))
s.addEventListener("activate", (event) => event.waitUntil(s.clients.claim()))

s.addEventListener("fetch", (event) => {
if (event.request.cache === "only-if-cached" && event.request.mode !== "same-origin") {
return
}

event.respondWith(
fetch(event.request)
.then((response) => {
Expand Down
12 changes: 9 additions & 3 deletions src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,18 @@ if (!window.isSecureContext) {
console.log("Not registering service worker because the site is not hosted on HTTPS.")
} else {
console.log("Registering service worker", import.meta.env.BASE_URL + 'sw.js')
navigator.serviceWorker.register(import.meta.env.BASE_URL + 'sw.js')
await navigator.serviceWorker.register(import.meta.env.BASE_URL + 'sw.js')
.then(registration => {
console.log(`Service worker registered: scope "${registration.scope}"`)
registration.addEventListener("updatefound", () => window.location.reload())
if (registration.active && !navigator.serviceWorker.controller) {
window.location.reload()
const installing = registration.installing
if (installing) {
installing.addEventListener("statechange", () => {
console.log(`Service worker ${installing.state}`)
if (installing.state === "activated") {
window.location.reload()
}
})
}
})
}
Expand Down

0 comments on commit 5034258

Please sign in to comment.