What is fetch(url) ?
Now instead of making our SW send simple responses, let’s go to the network for the response using the fetch(url) API.
fetch(url) lets you make network requests and lets you read the response.
It performs a normal browser fetch, so the results may come from the cache,
which can be a benefit as we want much of our content to be cached as usual.
An example of a simple use of the fetch
API.
fetch('/imgs/logo.png');
An example of an elaborate use of the fetch
API.
fetch('/foo').then(function(response) {
return response.json();
}).then(function(data) {
console.log(data);
}).catch(function() {
console.log('It failed')
})
Request URL
We’ve never handled getting a URL over a request yet. So to know where to start, you can:
1. Google MDN Request.
This should help you see what methods can come in handy for this task.
2. Inspect the Request object
Alternatively, you can add a console log and log out event.requests
,
and check out the Request object in the Console panel after you’ve checked preserve log.
self.addEventListener('fetch', function(event) {
console.log(even.request);
event.respondWith(
fetch('/imgs/dr-evil.gif')
);
});
event.respondWith
takes either a response or a promise that resolves to a response.
fetch()
takes a full request object as well as a URL, and returns a promise that resolves to a response.
Selective Response Depending on Request URL
Let’s serve a GIF image in response to a particular requests, say to any JPG request.
To accomplish this task, this is how you respond to requests selectively.
self.addEventListener('fetch', function(event) {
if (event.request.url.endsWith('.jpg'))
event.respondWith(
fetch('/imgs/dr-evil.gif')
);
});