Why are preload link not working for JSON requests ?

后端 未结 9 577
星月不相逢
星月不相逢 2020-12-30 02:24

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

相关标签:
9条回答
  • 2020-12-30 02:54

    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

    0 讨论(0)
  • 2020-12-30 02:55

    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.

    0 讨论(0)
  • 2020-12-30 02:55

    Try as="object". Seems to work for me:

    <link rel="preload" href="/test.json" as="object">
    
    0 讨论(0)
  • 2020-12-30 03:00

    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">

    0 讨论(0)
  • 2020-12-30 03:01

    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

    0 讨论(0)
  • 2020-12-30 03:02

    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.

    0 讨论(0)
提交回复
热议问题