Javascript 如何判断 XMLHTTPRequest 是否命中浏览器缓存

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13783442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:53:30  来源:igfitidea点击:

How to tell if an XMLHTTPRequest hit the browser cache

javascriptxmlhttprequestbrowser-cache

提问by rjkaplan

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

如果可以(在 javascript 执行中)判断 GET XMLHTTPRequest 是否命中浏览器缓存而不是从服务器获取响应?

回答by Feross

From the XMLHttpRequest spec:

XMLHttpRequest 规范

For 304 Not Modified responses that are a result of a user agent generated conditional request the user agent must act as if the server gave a 200 OK response with the appropriate content.

对于由用户代理生成的条件请求导致的 304 Not Modified 响应,用户代理必须像服务器提供具有适当内容的 200 OK 响应一样。

In other words, the browser will always give status code 200 OK, even for requests that hit the browser cache.

换句话说,浏览器总是会给出状态码 200 OK,即使是请求访问了浏览器缓存。

However, the spec also says:

但是,规范还说:

The user agent must allow author request headers to override automatic cache validation (e.g. If-None-Match or If-Modified-Since), in which case 304 Not Modified responses must be passed through.

用户代理必须允许作者请求头覆盖自动缓存验证(例如 If-None-Match 或 If-Modified-Since),在这种情况下,必须传递 304 Not Modified 响应。

So, there is a workaround to make the 304 Not Modified responses visible to your JavaScript code.

因此,有一种解决方法可以使 304 Not Modified 响应对您的 JavaScript 代码可见。

回答by Ibu

When making an ajax request, You get the response code

发出ajax请求时,您会得到响应代码

if (request.readyState == 4) {
     if (request.status == 200) { // this number.
       ...

status 200 means you are getting a fresh copy of the data:

状态 200 表示您正在获取数据的新副本:

The request has succeeded. The information returned with the response is dependent on the method used in the request -

请求已成功。与响应一起返回的信息取决于请求中使用的方法 -

status 304 means the data has not changed and you will get it from the browser cache:

状态 304 表示数据未更改,您将从浏览器缓存中获取它:

If the client has performed a conditional GET request and access is allowed, but the document has not been modified, the server SHOULD respond with this status code.

如果客户端已经执行了一个有条件的 GET 请求并且允许访问,但是文档没有被修改,服务器应该用这个状态码来响应。

Read more on Status Code

阅读有关状态代码的更多信息

Update:
You can add a cache buster to your URL to guarantee that you always hit the server:

更新:
您可以在您的 URL 中添加一个缓存破坏者,以确保您始终访问服务器:

var ajaxUrl = "/path?cache="+(Math.random()*1000000);

回答by JayC

From http://www.w3.org/TR/2012/WD-XMLHttpRequest-20121206/

来自http://www.w3.org/TR/2012/WD-XMLHttpRequest-20121206/

For 304 Not Modified responses that are a result of a user agent generated conditional request the user agent must act as if the server gave a 200 OK response with the appropriate content. The user agent must allow author request headers to override automatic cache validation (e.g. If-None-Match or If-Modified-Since), in which case 304 Not Modified responses must be passed through. [HTTP]

对于由用户代理生成的条件请求导致的 304 Not Modified 响应,用户代理必须像服务器提供具有适当内容的 200 OK 响应一样。用户代理必须允许作者请求头覆盖自动缓存验证(例如 If-None-Match 或 If-Modified-Since),在这种情况下,必须传递 304 Not Modified 响应。[HTTP]

I find this rather vague. My assumption would be ifa resource is conditionally requested, you would see the 304 response code. But, as I explained in another comment (source: https://developers.google.com/speed/docs/best-practices/caching), there might not even be a request if the last response server http header for that resource had set Cache-Control: max-ageor Expiresset sometime in the future. In this case, I'm not sure what ought to happen.

我觉得这很模糊。我的假设是,如果有条件地请求资源,您会看到 304 响应代码。但是,正如我在另一条评论中所解释的(来源:https: //developers.google.com/speed/docs/best-practices/caching),如果该资源的最后一个响应服务器 http 标头具有设置Cache-Control: max-ageExpires设置在将来的某个时间。在这种情况下,我不确定应该发生什么。

回答by Sean Kinsey

This answer is based on the assumption that you mean browser only cache, with no 304's taking place (modified-since, etag etc).

这个答案是基于这样一个假设,即您的意思是浏览器仅缓存,没有发生 304(修改后,etag 等)。

Check how long the request took - if it was resolved from cache then it should take close to 0ms.

检查请求花费了多长时间 - 如果它是从缓存中解析的,那么它应该花费接近 0 毫秒。

回答by mhulse

Do you use Firefox's Firebug?

你使用 Firefox 的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".

Firebug 有一个带有“XHR”过滤视图的“Net”面板。您应该能够通过请求阶段栏检查缓存信息,检查状态和/或单击三角形以检查“标题”。

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 为每个请求提供状态代码,以便您可以快速扫描并查看您的站点使用缓存优化页面加载时间的效率。

Firebug Net Panel docs are here.

Firebug网络面板文档在这里

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

Chrome/Safari/Opera 都有类似的调试工具。刚刚在这里找到了一个很好的列表(大多数应该有检查 XHR 的工具)。



EDIT:

编辑:

In order to somewhat redeem myself...

为了某种程度的救赎……

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

正如ibu 所回答的那样,我也将从检查响应的状态代码开始。

If you're using jQuery:

如果您使用 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.

statusCode(已添加 1.5)Map Default:{} 响应具有相应代码时要调用的数字 HTTP 代码和函数的映射。例如,当响应状态为 404 时,以下内容将发出警报:

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

如果请求成功,状态码函数采用与成功回调相同的参数;如果导致错误,则它们采用与错误回调相同的参数。

jQuery sure does make life easy. :)

jQuery 确实让生活变得轻松。:)