How to tell if an XMLHTTPRequest hit the browser cache

后端 未结 5 1531
别跟我提以往
别跟我提以往 2020-12-25 12:13

If it possible to tell (within javascript execution) if a GET XMLHTTPRequest hit the browser cache instead of getting its response from the server?

5条回答
  •  囚心锁ツ
    2020-12-25 13:07

    Do you use Firefox's Firebug?

    Firebug has a "Net" panel with an "XHR" filtered view. You should be able to inspect the cache info via the request phase bar, checking the status and/or clicking the triangle to inspect "Headers".

    Cached or not cached

    Not all network requests are equal - some of them are loaded from the browser cache instead of the network. Firebug provides status codes for every request so you can quickly scan and see how effectively your site is using the cache to optimize page load times.

    Firebug Net Panel docs are here.

    Chrome/Safari/Opera all have similar debugging tools. Just found a good list here (most should have tools to inspect XHR).


    EDIT:

    In order to somewhat redeem myself...

    As ibu has answered, I'd also start by checking the status code of the response.

    If you're using jQuery:

    statusCode(added 1.5) Map Default: {} A map of numeric HTTP codes and functions to be called when the response has the corresponding code. For example, the following will alert when the response status is a 404:

    $.ajax({
      statusCode: {
        404: function() {
          alert("page not found");
        }
      }
    });
    

    If the request is successful, the status code functions take the same parameters as the success callback; if it results in an error, they take the same parameters as the error callback.

    jQuery sure does make life easy. :)

提交回复
热议问题