Tom Tucker
Tom Tucker

Reputation: 11916

Prevent Browsers from Cacheing certain JavaScript files

I have two types of JavaScript files. 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. The dynamic JavaScript file is generated once per session and I would like the client browser to cache it for the remainder of session.

How do I force the client browser to request a JavaScript file every session? 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. You can't really do that with sessions since there can be multiple sessions per day.

Upvotes: 1

Views: 278

Answers (3)

Jim Ferrans
Jim Ferrans

Reputation: 31012

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. It should be a lot easier just to set the HTTP 1.1 Cache-Control header in your response to "no-cache". If you're using Java Servlets, it's done this way:

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.)

Upvotes: 0

Matthew Crumley
Matthew Crumley

Reputation: 102745

Could you append the session id to the JavaScript URL? Assuming you're using JSP, it would look kind of like this:

<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.

Upvotes: 1

Shaz
Shaz

Reputation: 15877

I don't see what's wrong with placing a random number at the end of the JavaScript url. 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.

Upvotes: 2

Related Questions