Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are preload link not working for JSON requests ?

The JavaScript on my website loads several JSON to initialize itself.

I would like to preload them so, when the JavaScript will launch an Ajax request on it, they will be loaded instantaneously.

A new link tag exists for that.

I tried to use it to load a JSON like that :

<link rel="preload" href="/test.json">

However, Chrome seems to load it twice and present a warning in the console :

The resources test.json was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it wasn't preloaded for nothing.

So it seems that preload doesn’t work for JSON. Indeed, I haven’t found reference to JSON in the specification.

Is that correct or am I doing it wrong ?

like image 732
paulgreg Avatar asked Jan 14 '17 23:01

paulgreg


2 Answers

According to https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content , you have to add as="fetch" for JSON files. So your code becomes

<link rel="preload" href="/test.json" as="fetch">

It's supported by all modern browsers and you get a warning message if this resource is not used within a few seconds because it is counterproductive to "preload" it in a such case (delay, double load etc.)

It's different from <link rel="prefetch" ...> which is to anticipate future navigation and not supported widely.

A Chrome illustrated article about this: https://medium.com/reloading/preload-prefetch-and-priorities-in-chrome-776165961bbf

like image 194
J.P. Duvet Avatar answered Oct 06 '22 02:10

J.P. Duvet


If you have the same problem as me, your response is probably being sent with Vary: Accept, the preload request is sent with Accept: */*, and the fetch/xhr request is being made with Accept: application/json.

It seems like the preload Accept: behavior can't be changed (sigh), so you'll have to either remove the Vary: Accept, or make the fetch/xhr request with a matching Accept: header.

like image 38
Dan Avatar answered Oct 06 '22 01:10

Dan