Re: [ServiceWorker] Can caches store and retrieve results that are still being written to the cache? (#573)

I think the changes are right, but it doesn't solve the problems I thought it might:

```js
self.addEventListener('fetch', function(event) {
  var requestURL = new URL(event.request.url);

  if (/\.jpg$/.test(requestURL.pathname)) {
    event.respondWith(
      caches.match('/img.jpg').then(function(response) {
        return response || fetch('/img.jpg').then(function(response) {
          caches.open('img-cache').then(function(cache) {
            cache.put('/img.jpg', response.clone());
            return response;
          });
        });
      })
    );
  }
});
```

Imagine a page with `a.jpg` and `b.jpg`:

1. `a.jpg`: look for `/img.jpg` in caches
1. `b.jpg`: look for `/img.jpg` in caches
1. `a.jpg`: no match found
1. `a.jpg`: fetch `/img.jpg`
1. `b.jpg`: fetch `/img.jpg`
1. etc etc

Should we try to solve the above or leave it to devs? Devs could do it with something like:

```js
var imgRequest;

self.addEventListener('fetch', function(event) {
  var requestURL = new URL(event.request.url);

  if (/\.jpg$/.test(requestURL.pathname)) {
    event.respondWith(
      caches.match('/img.jpg').then(function(response) {
        if (response) return response;
        if (!imgRequest) {
          imgRequest = fetch('/img.jpg').then(function(response) {
            caches.open('img-cache').then(function(cache) {
              cache.put('/img.jpg', response.clone());
              return response;
            });
          });
        }

        return imgRequest.then(function(response) {
          return response.clone();
        });
      })
    );
  }
});
```

---
Reply to this email directly or view it on GitHub:
https://github.com/slightlyoff/ServiceWorker/issues/573#issuecomment-66486816

Received on Wednesday, 10 December 2014 17:13:42 UTC