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).
XHR responses are cached automatically in the browser cache if your HTTP cache headers permit it.
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.
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.
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.
The answer is Date header
e.g.
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");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With