可以使用链接预取来为以后的XHR请求缓存JSON API响应吗? [英] Can link prefetch be used to cache a JSON API response for a later XHR request?

查看:89
本文介绍了可以使用链接预取来为以后的XHR请求缓存JSON API响应吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于JSON API端点 / api / config ,我们正在尝试使用< link rel = prefetch href = / api / config> 放在HTML文档的开头。 Chrome浏览器在点击HTML中的链接标记后会按预期下载数据,但大约在一秒钟后又通过XHR从脚本中再次请求数据。

Given a JSON API endpoint /api/config, we're trying to use <link rel="prefetch" href="/api/config"> in the head of an HTML document. Chrome downloads the data as expected when it hits the link tag in the HTML, but requests it again via XHR from our script about a second later.

服务器配置为允许缓存,并在标题中使用 Cache-Control: max-age = 3600,必须重新验证 进行响应。当Chrome再次请求数据时,服务器会以304未修改状态正确响应。

The server is configured to allow caching, and is responding with Cache-Control: "max-age=3600, must-revalidate" in the header. When Chrome requests the data again, the server responds correctly with a 304 Not Modified status.

用例是这样的:始终会从Javascript中请求config终结点我们使用XHR的单页应用程序(如果相关,则为AngularJS解决方案)。但是,我们的脚本非常大,并且解析时间很长,因此在解析完成之前,不会请求JSON配置。预取将使我们能够使用其中的一些解析时间来获取和缓存来自API端点的响应,否则这些API端点必须等待脚本加载。

The use case is this: the config endpoint will always be requested from the Javascript in our single page application using XHR (an AngularJS resolve, in case it's relevant). However, our scripts are very large and take a long time to parse, so the JSON config will not be requested until the parsing is finished. Prefetching would allow us to use some of that parsing time to fetch and cache responses from API endpoints that would otherwise have to wait for the scripts to load.

推荐答案

是的,您应该可以预加载JSON 在此处阅读

Yes you should be able to preload JSON Read here.


fetch:将由fetch或XHR请求访问的资源,例如ArrayBuffer或JSON文件。

fetch: Resource to be accessed by a fetch or XHR request, such as an ArrayBuffer or JSON file.

因此,请尝试以下语法:

So try this syntax:

<link rel="preload" href="/api/config" as="fetch">

这篇关于可以使用链接预取来为以后的XHR请求缓存JSON API响应吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆