Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I add custom headers while trying to preload XHR data?

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?

like image 688
Ayush Avatar asked Mar 16 '21 05:03

Ayush


2 Answers

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?

like image 136
divinelemon Avatar answered Oct 03 '22 19:10

divinelemon


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.

like image 37
oieduardorabelo Avatar answered Oct 03 '22 17:10

oieduardorabelo