How to prevent request that returns 304

前端 未结 4 743
栀梦
栀梦 2020-11-30 23:59

When does a browser NOT make a request to the server for a file?

In other words, I have a JavaScript file being served. Its HTTP response header has an ETag

4条回答
  •  粉色の甜心
    2020-12-01 00:24

    Firstly, the relevant HTTP spec is RFC 7234. If you look at the spec you will observe two things:

    • The spec never requires, under any circumstances, that a cache serves a cached version of content without revalidating. There are plenty of places where the spec notes that a cache MUST NOT use cached content to satisfy a request, but none at all where it dictates that it MUST do so or that it MUST NOT revalidate. So browser vendors are always free to revalidate if they want to.

    • Secondly, you're doing nothing wrong on your end. Browsers are free to cache responses and use those cached responses given the headers you're returning. The key point is in Section 4, where it is noted that one of the conditions for serving a cached response is that the response is either:

      • fresh (see Section 4.2), or

      • allowed to be served stale (see Section 4.2.4), or

      • successfully validated (see Section 4.3).

      Since you're spitting out an Expires header that is far in the future, and that point in the future has not yet been reached, the response is 'fresh', and therefore revalidation is not required. So you're doing everything that the spec suggests you should be on your end. (Although using Cache-Control: max-age=foo is a more modern way of setting cache expiry times than using the Expires: header.)

    So if you want to change the browsers' caching behaviour, you're out of luck.

    However, things might not be as bad as you think. You're probably only be seeing a request and 304 because you're refreshing the page in your browser when testing. Browsers handle cached resources differently depending upon how the request for them was triggered.

    I ran a simple test in which I created a HTML page that contained a

提交回复
热议问题