I am using the service worker to cache requests made ot a rest service. The implementation corresponds to 'on network response' described on this page https://web.dev/offline-cookbook/.
self.addEventListener('fetch', function (event) {
event.respondWith(
caches.open('mysite-dynamic').then(function (cache) {
return cache.match(event.request).then(function (response) {
return (
response ||
fetch(event.request).then(function (response) {
cache.put(event.request, response.clone());
return response;
})
);
});
}),
);
});
The idea is that:
1. caller makes 1st request A
2. service worker intercepts the request A
3. service worker checks whether a request A is in storage -> no
4. service worker sends the request A to the rest service
5. service worker gets the response A
6. service worker stores the response A
7. service worker returns the response A to the caller
...
8. caller makes 2nd request A
9. service worker intercepts the request A
10. service worker checks whether a request A is in the cache -> yes
11. service worker gets the response A from storage
12. service worker returns the response A to the caller
The problem is that the rest request takes some time to return a response and this scenario where 2 or more requests are made to the rest service can occur:
1. caller makes 1st request A
2. service worker intercepts the request A
3. service worker checks whether a request A is in storage -> no
4. service worker sends the request A to the rest service
5. caller makes 2nd request A
6. service worker intercepts the request A
7. service worker checks whether a request A is in storage -> no
8. service worker gets the response A
9. service worker stores the response A
10. service worker returns the response A to the caller
11. service worker gets the response A
12. service worker stores the response A
13. service worker returns the response A to the caller
How to have only 1 request sent?
fetch
is executed. And you cannot put the promise in the builtincache
, and you'll have to choose the resource identifier (URL?) by which your cache is keyed. – Bergi