How to detect when XHR returns a cached resource?

我是研究僧i 提交于 2019-11-30 01:45:19

问题


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


回答1:


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



回答2:


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");
    }
} 



回答3:


Apparently we can also use the Resource Timing API to determine whether something was served from browser cache; if the transferSize is 0 (and the encodedBodySize is >0) then that's a cache hit.

That seems like a better solution than the others, as long as you're dealing with a browser that supports it.

Ref: https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming/transferSize



来源:https://stackoverflow.com/questions/12830425/how-to-detect-when-xhr-returns-a-cached-resource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!