简体   繁体   English

强制浏览器仅在更改后才重新加载css / js

[英]Forcing the browser to reload css/js only if they have changed

There are a lot of questions and answers on SO related to my problem [I want the browser to cache js/css forever. 关于我的问题,有很多关于SO的问题和答案[我希望浏览器永远缓存js / css。 During a new release if some of the js/css files have been updated, the browser should reload and cache them.] 在新发行版中,如果某些js / css文件已更新,则浏览器应重新加载并缓存它们。]

This solution seemed most appropriate to me : What is an elegant way to force browsers to reload cached CSS/JS files? 这个解决方案对我来说似乎最合适: 什么是强制浏览器重新加载缓存的CSS / JS文件的优雅方法?

However, there is just one thing that I am unable to figure out. 但是,只有一件事我无法弄清楚。 The solution makes use of last_modified_time. 该解决方案利用了last_modified_time。 However, I am not allowed to use it. 但是,我不允许使用它。 I need to use some other mechanism. 我需要使用其他机制。

What are the options? 有什么选择? Is there a possibility of pre-calculating the versions during build and updating(replacing) them in jsps via build script (before deployment, so that the version numbers are not calculated on run time)? 是否有可能在构建过程中预先计算版本并通过构建脚本在jsps中更新(替换)它们(在部署之前,这样就不会在运行时计算版本号)? Any existing tool for this purpose? 为此目的有任何现有工具吗? I use Java/Jsp. 我使用Java / Jsp。

We always use 我们总是用

file.css?[deploytimestamp]

This way the CSS file is cached for each deployment at the client. 这样,将为客户端的每个部署缓存CSS文件。 The same goes for our minified javascript. 我们的小型javascript也是如此。 Is this an option for you? 这是您的选择吗?

It may not be the best way, but this is what I am doing now: 这可能不是最好的方法,但这就是我现在正在做的事情:

  1. All of my js/css have a [source control = svn] revision number 我所有的js / css都有一个[source control = svn]修订版号
  2. References in my jsp are like /foo/path1/path2/xyz000000/foo. 我的jsp中的引用类似于/ foo / path1 / path2 / xyz000000 / foo。
  3. Build Step 1 - Generate a map of css|js files and their revision numbers 构建步骤1-生成css | js文件及其修订号的映射
  4. Build Step 2 - Replace xyz000000 references in jsps with a hash of svn revisions 构建步骤2-用svn版本的哈希值替换jsps中的xyz000000引用
  5. A rule in url rewriter to direct all /foo/path1/path2/xyz<767678>/foo. url重写器中的规则用于定向所有/ foo / path1 / path2 / xyz <767678> / foo。 to /foo/path1/path2/foo.[js|css] 到/foo/path1/path2/foo。[js|css]
  6. Infinitely cache the css|js files 无限缓存css | js文件
  7. Whenever there is a commit, the revision number changes and so do the references in .jsp 只要有提交,修订号就会更改,.jsp中的引用也会更改

Generate an md5-hash of each css file after deployment. 部署后为每个css文件生成一个md5-hash。 Use this hash instead of the timestamp in the url of the css. 使用此哈希代替CSS网址中的时间戳。

file.css?[hash of file.css contents]

It may be wise to calculate the hashes once after deployment and store them to gain some performance. 部署后一次计算哈希并存储它们以获得一些性能可能是明智的。 You could store them in a database, or even in a PHP array in a separate file that is included in your website code. 您可以将它们存储在数据库中,甚至可以存储在网站代码中包含的单独文件中的PHP数组中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM