Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 387
bsa Avatar asked Jul 26 '16 15:07

bsa


2 Answers

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">
like image 143
Jens Avatar answered Nov 12 '22 01:11

Jens


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 need it for future navigation is quite similar to prefetching an image before the user navigates to it.

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

like image 45
Okoch Avatar answered Nov 12 '22 03:11

Okoch