Search code examples
ajaxhttphttp-headersxmlhttprequesthttp-caching

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).


Solution

  • 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