How To Make Dynamic Versioning For CSS and JS Files

Why to Make Dynamic Version of CSS and JS Files

If you are developing a web application in HTML and CSS or any other technology, and you are using some external CSS or JS files, you might notice one thing that in some cases if you made any changes to your existing .css or .js files then the browsers are not reflecting the changes immediately.

What happens in that case is that the browser do not download a fresh copy of the latest version of the .css and .js files, instead it uses those files stored in your local cache. As a result the changes you made recently are not visible to you.

How to Add Version to the File Names

In this case if you want your results to be effective in your browser then you may need to refresh your browser or you may need to clear the cache of your browser so that it can download a fresh copy from the server. Or else there is a simple way to achieve this.

This is a very common problem in day to day codding life. Here is a simple way that explains how to fool around the browser and force it to download a fresh content of the .css or .js file.

Below is a stylesheet which has a source file "style.css" that end with a query string like thing "?v=1.1".
<link rel="stylesheet" href="style.css?v=1.1"> 
The above case when you load the web page the browser will treat "style.css"  as a different file along with "?v=1.1". Hence the browser is forced to download a fresh copy if the stylesheet or the script file.

Dynamically Add Version to the Javascript and CSS file Names:

If you want to do this versioning in a dynamic way then you can achieve this by using the config file in

Let's say you are using a single style.css file in multiple locations, then there will be a bit problem when you change something in the file and forget the locations where the file is being used. There you can not add the versioning query string manually.

In this case you need a dynamic way to do this and here I achieved this using the config file in

Just add a key inside the appsettings of your config file as below.
    <add key="Version" value="1.1"/>
Now in the page where the .css or .js files are being used, append the below code to the "src" attribute.
<script src="Scripts/ModalPopUp.js?v=<%= System.Configuration.ConfigurationManager.AppSettings["Version"] %>" type="text/javascript"></script>
This will automatically append the query string "v=1.1" to the "src"  attribute of the link. And in future if you change anything in the .css or .js file then no need to find out all the locations to add versions, just change the version in the config file and your work is finished. You just make the browser fool to download a fresh copy.

Happy Coding...

No comments:

Post a Comment