- From: Ricky Miller <notifications@github.com>
- Date: Tue, 08 Jan 2019 19:39:39 -0800
- To: w3c/ServiceWorker <ServiceWorker@noreply.github.com>
- Cc: Subscribed <subscribed@noreply.github.com>
- Message-ID: <w3c/ServiceWorker/issues/1373/452561347@github.com>
@jakearchibald
> We could also add things like { url: { pathStartsWith: '/foo/' } } to match against particular components of the URL, but you'd be matching against all origins unless you specify otherwise.
I think that's fine because sometimes we care about checking the domain and we don't at other times. Here's some code that's more-or-less exactly what I'm doing on a real-world service worker.
```javascript
self.addEventListener('fetch', function(event) {
const request = event.request;
event.respondWith(
caches.match(request)
.then(function(response) {
if (response) {
return response;
}
const url = new URL(request);
if(url.pathname == '/some_path') {
const redirectUrl = new URL(url.href);
redirectUrl.pathname = '/';
return Response.redirect(redirectUrl.href,302);
}
if(url.hostname == IMAGE_CDN_HOSTNAME) {
return fetchFromImageCdn(request);
}
return fetch(request);
})
);
});
function fetchFromImageCdn (request) {
// basically fetch once and cache forever
}
```
Technically, both `https://mywebsite.foo/some_path` and `https://myimagecdn.foo/some_path` will both redirect to `/`, but I know that the page will never try to access `https://myimagecdn.foo/some_path` so it's fine that both match.
I'd like to use declarative routing to do something like this
```javascript
// Things that try the cache, then go to the network
const cacheThenNetwork = [RouterSource.cache(), RouterSource.network()];
// These paths match all domains, but I'm only using one so it's fine
router.get(RouterCondition.url.pathname.is('/'), cacheThenNetwork)
router.get(RouterCondition.url.pathname.startsWith('/static/'), cacheThenNetwork)
// Any path on the image CDN
router.get(RouterCondition.url.hostname.is(MY_IMAGE_CDN), cacheThenNetwork)
// fetch event listener can now be simplified
self.addEventListener('fetch', function(event) {
const request = event.request;
const url = new URL(request);
if(url.pathname == '/some_path') {
const redirectUrl = new URL(url.href);
redirectUrl.pathname = '/';
event.respondWith(Response.redirect(redirectUrl.href,302));
}
});
```
--
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/w3c/ServiceWorker/issues/1373#issuecomment-452561347
Received on Wednesday, 9 January 2019 03:40:01 UTC