我想预取一个JSON资源,并在以后必要时在我的JavaScript代码中使用它。
我正在预取:
<link rel="prefetch" href="/data.json" as="fetch">
但是我不知道如何访问该资源。在加载和缓存数据时,我认为一个fetch
请求将使用缓存,但是它正在向服务器发出第二个请求(我想避免)。
// a second request is sent to server instead of using the cache
fetch('/data.json').then(console.log);
答案 0 :(得分:0)
您要使用“预加载”而不是“预取”,例如:
<link rel="preload" href="/data.json" as="fetch"/>
在此线程上查看答案:Can link prefetch be used to cache a JSON API response for a later XHR request?
并检出mdn文档以进行预加载:https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content
答案 1 :(得分:0)
我使用的Chrome DevTools启用了禁用缓存(打开DevTools时)选项,因此fetch
总是向服务器发送新请求,而无需查看缓存。禁用此选项后,可以从缓存中正确检索资源。
在上图(DevTools网络选项卡)中,第一行显示了使用prefetch
对服务器的请求:
<link rel="prefetch" href="/data.json" as="fetch">
第二行表明我已经完成了fetch
,但是浏览器没有再次进入服务器,而是从缓存中加载了资源。
我已经使用以下命令访问了JSON文件:
// executed in a click event after the data.json was already prefetched
fetch('/data.json')
.then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response.json();
})
.then(json => {
console.log(json); // do something
})
.catch(console.error);