Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is including a hash in a filename better for caching than appending a timestamp as a query parameter?

While working with Grunt builds, I've come across the rev task and the cachebreaker task for revision / cache busting of static assets.

One uses file name overwrites, and the other adds a timestamp as a query param. And apparently, one is more preferable than the other.

Why is one better than the other?

like image 323
Kristian Avatar asked Aug 28 '14 20:08

Kristian


1 Answers

One of the comments on the link you provided says it best:

"Once you have unique names you can use very aggressive caching headers too, which is great for performance."

With a timestamp you have this version in their example:

<script type="text/javascript" src="@routes.Assets.at("javascripts/main.js")?nocache=@(new Date().getTime())"></script>

It adds a unique timestamp each time the script is requested. This means the browser never caches it.

Alternative, but similar method is to add an internal counter. Something like this:

<script type="text/javascript" src="@routes.Assets.at("javascripts/main.js")?version=1234"></script>

This one is a little better - because each time you change something in your assets, you change the version number. The browser would then load a version only once, and hold it in cache until you build a new version of your static assets.

The downside is that you have to somehow keep track of the version number. You can use something static, like a part of git commit, but still watch over this version + then you're dependant on git (or svn or whatever you use).

The hash version, such as javascripts/main.ab4c6c83e4fa9c.js has these benefits:

  • it is related only to one file - so it will depend just on main.js. Whatever you use in your other grunt tasks, we just care about main.js. You don't care about dates or versions or anything.
  • it is related only to the file contents. So if you change your js code, you will generate different content (say, from minifiers), so the hash will be different. The browser will be forced to load the new version.
  • if you change the content again to be the same as before (not just revert to that version, but also come to the same point in a future version), the hash of that content will be the same as the one that the browser already has in cache.

So with these, you don't care about dates, files, anything, you just create your Javascript. You also tell the browser to cache it for as long as it will, like a year or forever. And you're certain that if you switch between versions, the user gets the correct one.

like image 56
Zlatko Avatar answered Nov 03 '22 05:11

Zlatko