I have the following code in my service worker:
self.addEventListener('fetch', function (event) {
var fetchPromise = fetch(event.request);
fetchPromise.then(function () {
// do something here
});
event.respondWith(fetchPromise);
});
However, it's doing some weird stuff in the dev console and seems to be making the script load asynchronously instead of synchronously (which in this context is bad).
Is there any way to listen for when a request is completed without calling fetch(event.request)
manually?
For example:
// This doesn't work
self.addEventListener('fetch', function (event) {
event.request.then(function () {
// do something here
});
});
You can look at Service Worker Detector, a Chrome extension that detects if a website registers a Service Worker by reading the navigator. serviceWorker.
Service Workers are a special type of Web Worker with the ability to intercept, modify, and respond to all network requests using the Fetch API. Service Workers can access the Cache API, and asynchronous client-side data stores, such as IndexedDB , to store resources.
Examples of personal service positions include: medical assistants and other healthcare support positions, hairdressers, ushers, and transportation attendants. Examples of cleaning service positions include: cleaners, janitors, and porters.
Using a Service worker you can easily set an app up to use cached assets first, thus providing a default experience even when offline, before then getting more data from the network (commonly known as Offline First).
If you want to ensure that your entire series of actions are performed before the response is returned to the page, you should respond with the entire promise chain, not just the initial promise returned by fetch.
self.addEventListener('fetch', function(event) {
event.respondWith(fetch(event.request).then(function(response) {
// The fetch() is complete and response is available now.
// response.ok will be true if the HTTP response code is 2xx
// Make sure you return response at the end!
return response;
}).catch(function(error) {
// This will be triggered if the initial fetch() fails,
// e.g. due to network connectivity. Or if you throw an exception
// elsewhere in your promise chain.
return error;
}));
});
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