Why is including a cache in the file name better for caching than adding a timestamp as a request parameter?

While working with Grunt builds, I came across the rev task and the cachebreaker task to iterate over / cache static assets.

One uses the file name, and the other adds a timestamp as a request parameter. And, apparently, one is preferable to the other.

Why is one better than the other?

+5
source share
1 answer

One of the comments on the link you provided says better:

"When you have unique names, you can also use very aggressive caching headers, 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 every time a script is requested. This means that the browser never caches it.

An alternative but similar method is to add an internal counter. Something like that:

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

This is a little better - because every time you change something in your assets, you change the version number. Then the browser will download the version only once and keep it in the cache until you create a new version of your static assets.

The downside is that you need to somehow track the version number. You can use something static as part of git commit, but still keep track of this version +, then you depend on git (or svn or what you are using).

A hash version such as javascripts/main.ab4c6c83e4fa9c.js has the following advantages:

  • it is associated with only one file, so it will depend only on main.js. No matter what you use in your other grumbling tasks, we just care about main.js. You do not need dates, versions or anything else.
  • this is only related to the contents of the file. Therefore, if you change your js code, you will create different content (say from minifiers), so the hash will be different. The browser will have to download the new version.
  • if you change the content again so that it is the same as before (not just go back to this version, but also go to the same point in the future version), the hash of this content will be the same as the one that the browser already has in cache.

This way you don't need dates, files, whatever, you just create your Javascript. You also tell the browser to cache it as long as it takes, for example, a year or forever. And you are sure that if you switch between versions, the user gets the right one.

+7
source

Source: https://habr.com/ru/post/1201361/


All Articles