Is it possible to get service workers to wait to begin processing fetch events until asynchronous work completes at service worker startup?
I have an app shell with routes defined in data. To install specific route fetch handlers at service worker startup, I need to lookup route data from IndexedDB (asynchronous).
Unfortunately, the service worker starts accepting fetch events before the IndexedDB lookup can complete and setup fetch handling for routes.
For now, I'm just hardcoding a special case default handler for this, but it would be great to get the service worker to just delay processing fetch events until the IndexedDB processing is complete at service worker startup.
I didn't see a way to "waitUntil" for this, maybe I missed it?
A code snippet would help as I'm not 100% clear on the issue... But making a few guesses:
Until you resolve the promise provided to event.waitUntil when you listened for the install event, the SW shouldn't intercept any network requests, so doing the IDB set up there should be fine.
In general it's also fine just to have the fetch event listener run and not do anything, as the browser will fall back to the network as normal in that case.
In general it's also worth beading in mind that SWs can and do get killed frequently so local variables won't stick around between receiving different events. If there's some data you will need when handling a different event, you should keep it in IDB or the Cache API and fetch it from there again.
There is a workaround:
function startupAsyncStuff() {
return new Promise(function (fulfill, reject) {
// put here your async stuff and fulfill the promise when done.
});
}
// Launch your startup async code
var asyncStuffDone = startupAsyncStuff();
// On fetch, wait for the former promise to be resolved first
self.onfetch = function (event) {
event.respondWith(asyncStuffDone.then(function () {
// your fetch handling code
}));
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With