When we access any web application, our browser hits the server and gets all the required resource/content files and cache those for further requests to avoid latency and improve a performance of the application.

This browser cache will be a problem in case if there are any changes to these resource or content files at the server end, and these changes should reflect whenever user visit this application for the next time. But in most of the cases, the browser will check for these files in their cache. If it found then it won’t get latest files from a server and lost the latest changes at the client end.

To solve this issue we need to inform the browser that there are some changes to the files (JavaScript or CSS or images) and this time pick it from the server and update in your cache. To do so we need to append some query string kind of text at the end of each file, such that every time this string changes browser/cache-system treats it as a new file and requests the server for the latest version.

Following are the different approaches can be used.

Static Approach

Whenever the files are updated, all references to the files could be manually updated to increment a version number as follows.

<script type="text/javascript" src="~/Scripts/config.js?v=1"></script>

If there are any updates now increment the version from 1 to 2 as below

<script type="text/javascript" src="~/Scripts/config.js?v=2"></script>

Note: Instead of the number we can have any number or string which uniquely identifies it, for example, may be any hash string or GUID string.

Advantages

  • The browser will request for new file request in case there is a change in the version string. If there is no change then it will get from its cache system and improves performance.

Disadvantages

  • If we forget to update or change the version string at any file then the functionality might not work as expected. This can be avoided in case we are using any bundling tools like gulp or web pack.

Dynamic Approach

In this approach, the developer always appends current server date time ticks such that every time a browser treat it as a new request and always get the latest version from the server irrespective of files updated or not.

MVC:  

<script type="text/javascript" src="~/Scripts/config.js?v=@(DateTime.Now.Ticks)"></script>

 

Advantages

  • No need to worry about forgetting to update the version string as every time this will be changed automatically irrespective of changes or updates.

Disadvantages

  • There will be a lot of performance issue as for every request client browser should request for the file(s).
  • It will use lots of bandwidth and especially on slow networks.
  • Not much utilizing the browser cache system feature.

Happy Coding 🙂