Can link rel=preload be made to work with fetch?

梦想与她 提交于 2020-05-26 04:10:46

问题


I have a large JSON blob I would like to have preloaded with my webpage. To do this, I have added <link rel="preload" as="fetch" href="/blob.json"> to my page. I also have a JS request to fetch the same blob.

This does not work, and the console reports:

[Warning] The resource blob.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.

MDN claims that this can be fixed by adding crossorigin to the link tag. AFAICT, this is not true, and no combination or crossorigin attributes will actually make it work.

Using the copy-as-curl command from the developer console, it seems like there is no combination of link tag plus attributes that will issue the same request as a fetch/XHR call in JS.

I would love to be wrong about this.


回答1:


It looks like this is a difference between Safari and Chrome. Safari posts the warning to console, but Chrome does not, so maybe adding crossorigin to the link element does solve the problem, but Safari has some kind of bug?




回答2:


Thanks to the discussion in this bug, I got fetch to work with preload in Chromium 67:

First, add crossorigin attribute to the preload link:

<link rel="preload" as="fetch" href="/blob.json" crossorigin="anonymous">

Second, add same-origin credentials to the fetch request:

fetch(url, {credentials: 'same-origin'}).then(response => {
    console.log(response);
});

Alternatively, you can use XMLHttpRequest instead of fetch (with XHR you don't need to add anything to the request), but only if you're not going to use responseType = 'blob' - it won't work due to another bug.



来源:https://stackoverflow.com/questions/52635660/can-link-rel-preload-be-made-to-work-with-fetch

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!