In our Fetch Request example (see Fetch Request live) we
create a new Request object using the relevant constructor, then fetch it
using a fetch() call. Since we are fetching an image, we run
Response.blob() on the response to give it the proper MIME type so it will be
handled properly, then create an Object URL of it and display it in an
<img> element.
js
const myImage = document.querySelector("img");
const myRequest = new Request("flowers.jpg");
window
.fetch(myRequest)
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.blob();
})
.then((response) => {
myImage.src = URL.createObjectURL(response);
});
In our Fetch Request with init example (see Fetch Request init live) we do the same thing except that we pass in an options object when we invoke fetch().
In this case, we can set a Cache-Control value to indicate what kind of cached responses we're okay with:
js
const myImage = document.querySelector("img");
const reqHeaders = new Headers();
// A cached response is okay unless it's more than a week old
reqHeaders.set("Cache-Control", "max-age=604800");
const options = {
headers: reqHeaders,
};
// Pass init as an "options" object with our headers.
const req = new Request("flowers.jpg", options);
fetch(req).then((response) => {
// …
});
You could also pass the init object in with the Request constructor to get the same effect:
js
const req = new Request("flowers.jpg", options);
You can also use an object literal as headers in init:
js
const options = {
headers: {
"Cache-Control": "max-age=60480",
},
};
const req = new Request("flowers.jpg", options);
The Using fetch article provides more examples of using fetch().