I am firing an XHR from JS code. This render-blocking XHR is fired on every page load, so I want to fetch it early in page's lifecycle, in parallel with JS and CSS resources. Inside my index.html
, I'll add the following code:
<head>
<link rel="stylesheet" href="style.css">
<link rel="preload" as="fetch" href="/xhr-to-be-fetched-early">
</head>
The XHR request needs some custom headers such as authorization
& Accept
. Is there any way to add these headers to link
tag, either inside HTML itself or via JS? Or is it impossible to cache such requests?
You cannot truly add headers to a <link>
tag, but you can stop the page from loading anything until the resource is fetched.
See something like this:
const promiseOfSomeData = fetch("URL.com", {
// This is where you set the headers
headers: {
'X-My-Cool-Header': 'here'
}
}).then(data => {
return data;
});
window.onload = async () => {
let someData = await promiseOfSomeJsonData;
console.log(someData)
};
How can I make "onload" waiting for "fetch" complete?
you can't add custom headers in the link
request; when you use as
to specify the type of content, browsers will automatically apply the correct headers based on the content type, but you don't have access to this lifecycle.
you could use a <script async></script>
instead, https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-async, and perform the fetch
with extra headers. It will be executed in parallel with other resources of the page.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With