Can link prefetch be used to cache a JSON API response for a later XHR request?

点点圈 提交于 2019-12-22 01:55:15

问题


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.

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.

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.


回答1:


Yes you should be able to preload JSON Read here.

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



回答2:


From MDN:

Link prefetching is a browser mechanism, which utilizes browser idle time to download or prefetch documents that the user might visit in the near future.

IMO, prefetching data for the user, before he needs it in its future navigation is quite similar to prefetch an image before he navigates to it.

Another approach can be done with web worker, fetching datas in a parallel thread.



来源:https://stackoverflow.com/questions/38593535/can-link-prefetch-be-used-to-cache-a-json-api-response-for-a-later-xhr-request

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