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

后端 未结 30 4347
青春惊慌失措
青春惊慌失措 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 05:58

    The 30 or so existing answers are great advice for a circa 2008 website. However, when it comes to a modern, single page application (SPA), it might be time to re-think some fundamental assumptions… specifically the idea that it is desirable for the web server to serve only the single, most recent version of a file.

    Imagine you're a user that has version M of a SPA loaded into your browser:

    1. Your CD pipeline deploys the new version N of the application onto the server
    2. You navigate within the SPA, which sends an XHR to the server to get /some.template
      • (Your browser hasn't refreshed the page, so you're still running version M)
    3. The server responds with the contents of /some.template — do you want it to return version M or N of the template?

    If the format of /some.template changed between versions M and N (or the file was renamed or whatever) you probably don't want version N of the template sent to the browser that's running the old version M of the parser.†

    Web apps run into this issue when two conditions are met:

    • Resources are requested asynchronously sometime after the initial page load
    • The app logic assumes things (that may change in future versions) about resource content

    Once your app needs to serve up multiple versions in parallel, solving caching and "reloading" becomes trivial:

    1. Install all site files into versioned dirs: /v/…files…, /v/…files…
    2. Set HTTP headers to let browsers cache files forever
      • (Or better yet, put everything in a CDN)
    3. Update all
提交回复
热议问题