Is a browser's HTTP cache ever used to store XMLHttpRequest responses?

Viewed 727

This is a question about browsers in general, but I'm primarily concerned with Chrome.

Let's say I have the following snippet in a file, index.html:

<img src='//path/to/foo.img'></img>

and foo.img changes on my server every hour. I want to prefetch this image on the hour so that when the user refreshes the page, the updated image //path/to/foo.img is read from the browser's HTTP cache.

There are a few things I'm uncertain about:

  1. Are the responses for XHRs cached at all by default?
  2. If so, do they use a separate cache from the one the browser uses when fetching things like img, css, js, etc. requests?
  3. If the answer to #2 is no, then is it sufficient to send an XHR for //path/to/foo.img in order to cause the response to be cached - and then re-used by the browser when the page is refreshed?
2 Answers

To force the browser to load a new version of a file that's already in cache, do the following:

  1. Create a hidden iframe with the <img> tag in that iframe
  2. Also add some JavaScript to that iframe that will call location.reload(true); This will force the iframe and all resources linked within it to reload from the server and repopulate the browser cache.
  3. Make sure it only calls it once, or you'll go into an infinite loop. You can do this by setting a cookie, or updating location.hash or checking resource timing to see if the resource was fetched over the network before the reload.

You can see http://www.lognormal.com/blog/2012/06/17/more-on-updating-boomerang/ and http://www.lognormal.com/blog/2012/06/05/updating-cached-boomerang/ for some details.

Related