Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect when XHR returns a cached resource?

I'm wondering if there is a way how to detect when a response is returned from a local cache? Is it possible?

The solution should be general and work for unconditional requests. In this case, the response code is always 200 OK, but XHR returns a cached resource for the second request (e.g. the first response contains Expires header, so there is no need to ask a server for a new resource before the expiration date).

like image 640
Filip Avatar asked Oct 11 '12 00:10

Filip


People also ask

Does the browser cache XHR?

XHR responses are cached automatically in the browser cache if your HTTP cache headers permit it.

Which method is used to deal with stale cache problem in HTTP proxy?

HTTP has a mechanism to transform a stale response into a fresh one by asking the origin server. This is called validation, or sometimes, revalidation. Validation is done by using a conditional request that includes an If-Modified-Since or If-None-Match request header.

Are HTTP headers cached?

Cache-Control is a HTTP cache header that contains a set of parameters to define the browser's caching policies in the client requests and server responses. When a client makes a request to the server, the browser can cache, or store copies of resources for faster access and lower latency.

What is response caching?

Response caching reduces the number of requests a client or proxy makes to a web server. Response caching also reduces the amount of work the web server performs to generate a response. Response caching is controlled by headers that specify how you want client, proxy, and middleware to cache responses.


2 Answers

The answer is Date header

  • If date header is before send date then a response is coming from a cache.
  • If date header is after date when a request was sent then a response is fresh.

e.g.

  • from cache: request was sent at 11:00, response date is 10:59
  • no cache: request was sent at 11:00, response date is 11:01
like image 107
Filip Avatar answered Oct 03 '22 22:10

Filip


Check to see if the status code returned is 304 (not modified) in the onreadystatechange function. Something along the lines of:

xmlhttp.onreadystatechange=function()
{
  if (xmlhttp.readyState==4 && xmlhttp.status==304)
    {
      alert("Cached");
    }
} 
like image 31
Kevin Bowersox Avatar answered Oct 03 '22 20:10

Kevin Bowersox