且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何强制客户端刷新 JavaScript 文件?

更新时间:2022-10-15 14:23:20

据我所知,一个常见的解决方案是在脚本的 src 链接中添加一个 ?.

例如:

<script type="text/javascript" src="myfile.js?1500"></script>

此时我认为没有比 find-replace 更好的方法来增加所有脚本标签中的这些版本号"了吗?

您可能有一个版本控制系统为您做这件事?例如,大多数版本控制系统都有一种在签入时自动注入修订号的方法.

它看起来像这样:

<script type="text/javascript" src="myfile.js?$$REVISION$$"></script>

当然,总会有更好的解决方案,例如这个一>.

We are currently working in a private beta and so are still in the process of making fairly rapid changes, although obviously as usage is starting to ramp up, we will be slowing down this process. That being said, one issue we are running into is that after we push out an update with new JavaScript files, the client browsers still use the cached version of the file and they do not see the update. Obviously, on a support call, we can simply inform them to do a ctrlF5 refresh to ensure that they get the up-to-date files from the server, but it would be preferable to handle this before that time.

Our current thought is to simply attach a version number onto the name of the JavaScript files and then when changes are made, increment the version on the script and update all references. This definitely gets the job done, but updating the references on each release could get cumbersome.

As I'm sure we're not the first ones to deal with this, I figured I would throw it out to the community. How are you ensuring clients update their cache when you update your code? If you're using the method described above, are you using a process that simplifies the change?

As far as I know a common solution is to add a ?<version> to the script's src link.

For instance:

<script type="text/javascript" src="myfile.js?1500"></script>


I assume at this point that there isn't a better way than find-replace to increment these "version numbers" in all of the script tags?

You might have a version control system do that for you? Most version control systems have a way to automatically inject the revision number on check-in for instance.

It would look something like this:

<script type="text/javascript" src="myfile.js?$$REVISION$$"></script>


Of course, there are always better solutions like this one.