强制 JavaScript 每天重新加载一次
如果 JavaScript 的 ?random 是当前日期 - 那么它会每天只加载一次吗?
<script type="text/javascript" src="http://external.example.com/bookmarklet.js?random"></script>
我的问题的背景是,我不希望它永远保留在缓存中,但我也在寻找一种方法来节省一些带宽并加快速度。 谢谢
If the JavaScript's ?random would be the current date - would it then loaded just once a day?
<script type="text/javascript" src="http://external.example.com/bookmarklet.js?random"></script>
The background of my question is that I don't want that it stays forever in the cache but I'm also looking for a way to save some bandwith and speed things up.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果用户的浏览器已缓存该文件,则在包含的 js 文件名末尾添加日期或时间戳确实会使其重新加载。
如果你想使用 JavaScript 来制作这个时间戳,你可以动态地包含你的外部 js 文件,如下所示:
我选择根据日、月和年制作时间戳,所以它每天都会改变。
Adding a date or timestamp onto the end of the included js filename does make it reload itself if it has been cached by the user's browser.
If you want to use JavaScript to make this timestamp you can dynamically include your external js file like so:
I have chosen to make a timestamp from the day, month, and year, so it will change everyday.
如果您的页面是用 PHP 生成的,您可以这样做:
If your page is generated with PHP, you could do this:
仅当该时间戳被调整为一天中的某个时间(例如午夜)时。这不能在 HTML 中完成,但我发现一些 PHP 可以完成这项工作: 来自 PHP 怪胎
Only if that timestamp was adjusted to a certain time of the day (midnight, for example). This can't be done in HTML, but I found some PHP that will do the job: from PHP Freaks
是的,这应该完全按照您的需要工作,只需注意您只写了日期部分,没有时间。
Yes, that should work exactly like you need, just note that you write only the date part, without the time.
甚至比每天一次更好,我认为只要 JavaScript 发生变化,或者作为近似值,当您升级或重新启动应用程序时,您就需要刷新客户端的缓存。不确定 PHP 中的最佳实践是什么,但在 Python 中,我会在应用程序启动时生成一个随机数,将其存储在全局变量中,并在您提供的资源的每个 URL 中使用它,无论是 JS 还是 CSS。像 jQuery 或 YUI 等库只需要在有新版本时重新加载,并且您可能希望从 CDN 提供它们。
Even better than once per day, I think you need to refresh the client's cache whenever the javascript changes - or as an approximation, when you upgrade or restart the application. Not sure what's the best practice in PHP, but in Python I would generate a random upon application startup, store it in a global variable, and use that in every URL of the resources you provide, be it JS or CSS. Libraries like jQuery or YUI etc. only need to be reload when there's a new release, and you might want to serve them from a CDN.