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

4.4k views Asked by At

There are a lot of questions and answers on SO related to my problem [I want the browser to cache js/css forever. During a new release if some of the js/css files have been updated, the browser should reload and cache them.]

This solution seemed most appropriate to me : What is an elegant way to force browsers to reload cached CSS/JS files?

However, there is just one thing that I am unable to figure out. The solution makes use of 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)? Any existing tool for this purpose? I use Java/Jsp.

3

There are 3 answers

0
TJ- On BEST ANSWER

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
  2. References in my jsp are like /foo/path1/path2/xyz000000/foo.
  3. Build Step 1 - Generate a map of css|js files and their revision numbers
  4. Build Step 2 - Replace xyz000000 references in jsps with a hash of svn revisions
  5. A rule in url rewriter to direct all /foo/path1/path2/xyz<767678>/foo. to /foo/path1/path2/foo.[js|css]
  6. Infinitely cache the css|js files
  7. Whenever there is a commit, the revision number changes and so do the references in .jsp
4
David Hellsing On

We always use

file.css?[deploytimestamp]

This way the CSS file is cached for each deployment at the client. The same goes for our minified javascript. Is this an option for you?

0
GolezTrol On

Generate an md5-hash of each css file after deployment. Use this hash instead of the timestamp in the url of the 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.