2

Behind the scenes, if all you do is fetch the headers of a website, does the browser go ahead and downloaded the site's body content, even if you don't want it?

For example, in the code below I only want this website's headers, but I do not want the browser to download the page itself:

async function logHeaders()
{
  let url = "https://randomuser.me/";
  let res = await fetch(url);
  res.headers.forEach((value,key)=>
  {
    console.log(key+':',value);
  });
}
logHeaders();

I want to know if the browser preemptively downloads this page's content, despite the fact that I'm not requesting that. If it does, is there a way that I can explicitly cancel that preemptive download attempt before it happens?

Lonnie Best
  • 9,936
  • 10
  • 57
  • 97
  • 2
    It looks like it does. Try `fetch('https://tc39.es/ecma262/')` (which is a random large page) and check your OS's network connectivity stats. Many KBs are downloaded even if `.text()` / `.json()` isn't called on the Response object. That's unfortunate – CertainPerformance May 03 '20 at 10:49
  • 2
    Maybe you could use AbortController to abort the request as soon as you get the headers, but that's really ugly – CertainPerformance May 03 '20 at 10:53
  • 3
    Have you tried making a request using the HEAD method? – mateleco May 03 '20 at 10:57
  • @mateleco I have not. Interesting. That looks promising. – Lonnie Best May 03 '20 at 10:59
  • @mbojko : Yes, indeed. Thanks to all. – Lonnie Best May 03 '20 at 11:04
  • 2
    As pointed out above, if you just want HTTP headers, you need to specify the HEAD method in the fetch call. Otherwise, fetch makes an HTTP GET request — which explicitly means *“return a response body along with the response headers”*. And so the browser makes a GET request, and the server sends back a response body along with the response headers — again, because in HTTP, that’s what GET means, and that’s what the fetch call is asking for. The browser receives the response body. Then the browser makes the response body available through the response object the fetch API exposes. That’s it. – sideshowbarker May 03 '20 at 11:15
  • 1
    To be clear on something: The browser isn’t “preemptively” downloading the page’s contents when the fetch call shown in the question is made. And the part of the question which says, *“despite the fact that I'm not requesting that”* is mistaken — because the code shown in the question is in fact explicitly telling the browser to “download” the response. And that’s because (as pointed out in my other comment) a fetch call with no method specified causes an HTTP GET request. And — to use the same terms as the question — an HTTP GET call is an explicit request to “download the page’s contents”. – sideshowbarker May 03 '20 at 11:29
  • @sideshowbarker : Thanks for making those details clear. – Lonnie Best May 03 '20 at 11:44

0 Answers0