0

When I fetch a page using GET request in javascript, does the browser cache it the same way as it does when I click that link or type it in address bar?

If not, since I have already fetched the page, is there a way that I can add it (programmatically) to the browser cache?

Neo
  • 2,905
  • 5
  • 22
  • 35
  • possible duplicate of [Prevent caching of AJAX call](http://stackoverflow.com/questions/367786/prevent-caching-of-ajax-call). This basically answers your question imho. And the only way to enforce caching is to send proper headers (some restrictions/browser differences e.g. due to SSL apply afaik). – nietonfir Oct 17 '13 at 21:55
  • @nietonfir - I don't think an questino/answer about preventing caching is a dup of one that's trying to force caching. They are different questions that require different answers. – jfriend00 Oct 17 '13 at 22:09
  • @jfriend00 I (obviously) disagree. OP asks if browsers cache XmlHttp requests and that's answered by the dup. But after reading the [help page](http://stackoverflow.com/help/duplicates) carefully again, I must concede that the flag was a bit rush on my part. Nice answer btw. – nietonfir Oct 18 '13 at 19:43

1 Answers1

0

When the browser fetches web pages, it is also using a GET request. Chances are that all GET requests go through the same caching mechanism in the browser, though there is no specification that formalizes how that works.

There is no programmatic way to add something to the browser's own cache other than just requesting the resource and letting the browser's cache do its normal thing with it. If you want to know if all common browsers will cache it in this way, then you need to make sure the server-side header settings are set appropriately (to allow it to be cached) and then test each browser to make sure it's cached like you want.

If you are staying within the same page and want to make sure something is not requested more than once from the same page, you can implement your own cache within that page's javascript code. You just store the result in a javascript variable the first time it is requested and then a function you implement to fetch this resource just checks your own local storage object to see if the resource is already here. If not, it requests it via a GET and then saves the result. You could make a simple version of this that was hardcoded to one particular resource or a more general version that saved the URL and result and a timestamp and implemented more typical caching behaviors.

If you want it to be cached across pages and your testing finds that the built-in browser caches are not adequate, then you can use Local Storage to store the data (probably with a timestamp) and then just check the local storage before requesting it with a GET request.

jfriend00
  • 580,699
  • 78
  • 809
  • 825