Home > Blockchain >  <link rel=preload> with additonal HTTP headers
<link rel=preload> with additonal HTTP headers

Time:09-11

I added a preload for my site like this <link rel=preload href=http://api.github.com/... as=fetch crossorigin=anonymous> which is fetch()ed later. It worked very well (the preload request sent to the remote server at the very beginning of loading, and answer came back, everything was fine).

Later I added an Authorization: Bearer ... to the fetch() call (because of other reasons), which is caused that the preload's HTTP headers do not match the later fetch's HTTP headers, so the entire preload result is not re-used anymore (Both Chrome and Firefox are correctly notify me about this).

I also tried to add the preload with Link HTTP header to the main page's response, but that did not help as well.

So the current sitation is this: I can't add the same Authorization header to preload request because it is simply not possible, so the two request are never will be the same, so the preload is useless anymore.

Please correct me and advise:

  • Is there a way to add that Authorization: Bearer ... to the preload request to?
  • OR is there a way to ask the browser to ignore that difference between to two request's headers?
  • OR any other idea?

CodePudding user response:

Web standards do not allow for such a possibility.

The Fetch standard defines the conditions under which prefetched resources may be used as follows:

To fetch, given a request request, […] run the steps below. […]

  1. If all of the following conditions are true:

    then:

    1. Let foundPreloadedResource be the result of invoking consume a preloaded resource for [request]

Having an Authorization header in the fetch request disqualifies it from reusing preloaded resources. Unless you happen to know of a non-standard extension that allows you to bypass this, this means there is no way to prefetch a resource with custom headers.

There are three ways you can resolve this: skip the Authorization header in the request proper, give up on preloading entirely, or reimplement prefetching yourself. That is, inject a script that fetches the resource early during page loading, preferably gated by network.connection && !network.connection.saveData, and stores it in your own cache, then simply look up the data there.

The order I listed those solutions is one of, in my opinion, decreasing appropriateness. Prefetching has been designed mostly for the sake of static resources that present the same to any user that may want to download them; as such, an Authorization header is not supposed to matter, so if you can get away with avoiding it, do. If authorization does matter, then maybe the resource isn’t such a great candidate for prefetching. If you insist though, you can do it manually.

  • Related