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 wi
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
Try as="xhr"
. Seems to be working for me in Chrome when I do a server push - that's not exactly the same as the HTML tag but if you are getting that resources via Ajax / XmlHttpRequest, this might fix it.
Try as="object"
. Seems to work for me:
<link rel="preload" href="/test.json" as="object">
You have to add not only as="fetch", but (based on this comment) also crossorigin="anonymous". This should work:
<link rel="preload" href="/test.json" as="fetch" crossorigin="anonymous">
Here is the approach that works both in Chrome and Safari.
<link rel="preload" as="fetch" href="/data.json">
fetch('/data.json', {
method: 'GET',
credentials: 'include',
mode: 'no-cors',
})
This answer contains more details and explanation why and how does it work https://stackoverflow.com/a/63814972/1387163
Turns out there has been a bug in Chrome for using the fetch
API combined with rel=preload
here. I solved this by using XMLHttpRequest
instead.
Even though it seems to have been fixed in Chrome 62 it seems like I could still reproduce this on my Chrome 63.