Background - I have a firebase web app that loads and runs perfectly offline (i.e aeroplane mode) and online with a good connection. The problem is very weak connections where navigator.onLine is true, but the connection is basically unusable. The app hangs until I turn aircraft mode on. According to the Firebase SDK docs there doesn't seem to be a method to initializeApp() offline. I have Firestore offline persistence enabled and it works great once the app is loaded.
Goal - use the service worker to block fetch network requests for about 2 seconds by returning an error to 'trick' Firebase into thinking the device is offline and load instantly, then unblock/allow all future fetch requests as normal
The problem - the code I have found and implemented below works great initially and the app now loads instantly in all network conditions, but as Firebase tries again every 10 seconds or so to make fetch requests, the service worker continuous to intercept them which I don't want.
How do I make the following code run once only in a service worker on the initial load?
addEventListener("fetch", (event) => {
event.respondWith(
(async function () {
console.log("blocking");
event.request.url.startsWith("https://") ? Response.error() : fetch(event.request);
return setTimeout(() => {
console.log("unblocked");
fetch(event.request);
}, 3000);
})()
);
});