How to force the browser to reload cached CSS/JS files?

后端 未结 30 4349
青春惊慌失措
青春惊慌失措 2020-11-21 05:49

I have noticed that some browsers (in particular, Firefox and Opera) are very zealous in using cached copies of .css and .js files, even be

30条回答
  •  太阳男子
    2020-11-21 06:12

    Say you have a file available at:

    /styles/screen.css
    

    your can either append a query parameter with version information onto the URI, e.g.:

    /styles/screen.css?v=1234
    

    or you can prepend version information, e.g.:

    /v/1234/styles/screen.css
    

    IMHO the second method is better for CSS files because they can refer to images using relative URLs which means that if you specify a background-image like so:

    body {
        background-image: url('images/happy.gif');
    }
    

    its URL will effectively be:

    /v/1234/styles/images/happy.gif
    

    This means that if you update the version number used the server will treat this as a new resource and not use a cached version. If you base your version number on the Subversion/CVS/etc. revision this means that changes to images referenced in CSS files will be noticed. That isn't guaranteed with the first scheme, i.e. the URL images/happy.gif relative to /styles/screen.css?v=1235 is /styles/images/happy.gif which doesn't contain any version information.

    I have implemented a caching solution using this technique with Java servlets and simply handle requests to /v/* with a servlet that delegates to the underlying resource (i.e. /styles/screen.css). In development mode I set caching headers that tell the client to always check the freshness of the resource with the server (this typically results in a 304 if you delegate to Tomcat's DefaultServlet and the .css, .js, etc. file hasn't changed) while in deployment mode I set headers that say "cache forever".

提交回复
热议问题