简体   繁体   English

防止浏览器缓存某些JavaScript文件

[英]Prevent Browsers from Cacheing certain JavaScript files

I have two types of JavaScript files. 我有两种JavaScript文件。 One contains static code and the other contains dynamic code which changes from session to session. 一个包含静态代码,另一个包含动态代码,动态代码会在会话之间变化。

The static JavaScript file should be cached whereas the dynamic one should be cached only for that session and then reloaded In next session. 应该缓存静态JavaScript文件,而应该仅为该会话缓存动态JavaScript文件,然后在下一个会话中重新加载。 The dynamic JavaScript file is generated once per session and I would like the client browser to cache it for the remainder of session. 动态JavaScript文件每个会话生成一次,我希望客户端浏览器在其余会话中缓存该文件。

How do I force the client browser to request a JavaScript file every session? 如何强制客户端浏览器在每个会话中都请求一个JavaScript文件? I know that a common practice is to append a request parameter containing a version number, but one can make only so many updates to a file so that you can manually update JavaScript references. 我知道一种常见的做法是添加一个包含版本号的请求参数,但是一个文件只能对文件进行如此多的更新,因此您可以手动更新JavaScript引用。 You can't really do that with sessions since there can be multiple sessions per day. 您实际上无法使用会话执行此操作,因为每天可能会有多个会话。

I don't see what's wrong with placing a random number at the end of the JavaScript url. 我看不到在JavaScript网址末尾放置随机数有什么问题。 For example: 例如:

http://www.example.com/myjavascript.js?r=1234

Won't necessarily stop it from cache'n, but if the number is different, the browser will load that js file again. 不一定会从cache'n停止它,但是如果数量不同,浏览器将再次加载该js文件。

Could you append the session id to the JavaScript URL? 您可以将会话ID附加到JavaScript URL吗? Assuming you're using JSP, it would look kind of like this: 假设您使用的是JSP,它将看起来像这样:

<script src="/script.js?session=<%= // code to get the session ID %>"></script>

I don't know much about JSP, so I can't help with the specifics, but that should give you a single, unique URL for the session. 我对JSP不太了解,所以我无法提供具体的帮助,但这应该为您提供会话的唯一URL。

Just appending a session id or a random number to the file name would solve your user experience problem, but it also clogs up all the HTTP caches with useless entries. 只需在文件名后附加会话ID或随机数即可解决您的用户体验问题,但同时也会阻塞所有HTTP缓存中无用的条目。 It should be a lot easier just to set the HTTP 1.1 Cache-Control header in your response to "no-cache". 仅将响应中的HTTP 1.1 Cache-Control标头设置为“ no-cache”应该容易得多。 If you're using Java Servlets, it's done this way: 如果您使用的是Java Servlet,则可以通过以下方式完成:

response.setHeader("Cache-Control", "no-cache");  

(If some of your traffic will come from legacy browsers, http://onjava.com/pub/a/onjava/excerpt/jebp_3/index2.html gives some other header settings to really make sure nothing gets cached.) (如果您的某些流量来自旧版浏览器,则http://onjava.com/pub/a/onjava/excerpt/jebp_3/index2.html会提供其他一些标头设置,以确保没有缓存任何内容。)

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

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