Skip to content

Commit

Permalink
waiting for active Service Worker first
Browse files Browse the repository at this point in the history
thanks, Chromium browsers
  • Loading branch information
StrawberryMaster committed Jan 21, 2025
1 parent 2c623c2 commit dc9638e
Showing 1 changed file with 26 additions and 11 deletions.
37 changes: 26 additions & 11 deletions service-worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,19 +91,34 @@ self.addEventListener('install', event => {
);
});

self.addEventListener("fetch", async (event) => {
const request = event.request;
function waitForActiveServiceWorker() {
return new Promise(resolve) => {
if (self.registration.active) {
resolve(self.registration);
} else {
self.addEventListener('activate', () => {
resolve(self.registration);
});
}
});
}

if (!isCachable(request)) {
event.respondWith(fetch(request));
return;
}
self.addEventListener('fetch', async (event) => {
event.respondWith(
waitForActiveServiceWorker().then(() => {
const request = event.request;

if (isImage(request)) {
event.respondWith(staleWhileRevalidate(request));
} else {
event.respondWith(cacheFirstWithRefresh(request));
}
if (!isCachable(request)) {
return fetch(request);
}

if (isImage(request)) {
return staleWhileRevalidate(request);
} else {
return cacheFirstWithRefresh(request);
}
})
);
});

self.addEventListener('activate', event => {
Expand Down

0 comments on commit dc9638e

Please sign in to comment.