How to prevent browser to cache JavaScript and CSS file

Suppose your JavaScript and CSS files refer to your master page and you modify the piece of JavaScript code or CSS Style in these files the change are not reflected after that you debug the code and found your code changes are missing. In this tutorial, I show how to prevent browser to cache JavaScript and CSS files.

To resolve this you do a hard refresh(ctrl+f5) but this only resolves the issue on your machine. if you have a large organization suppose 500 or more users, you don’t ask everyone to force refresh the page to see the changes.

This is how the browser caches the file and resolves this for everyone so that no one needs to hard refresh the page.

How to prevent browser to cache JavaScript and CSS file

Prevent browser to cache JavaScript and CSS file

To fix the issue manually add a random version to the file. What I mean is just open the file where you refer your JavaScript and CSS like in your master page and find the JavaScript or CSS reference and add random version like below –

<script type="text/javascript" src="/scripts/jscustom.js?v=1">

This is the JavaScript reference and here in “src” I have added “?v=1”. v is the version and equal to(=) 1 you can use any random number or date in version value and this needs to update each time you made changes in the referred file.

Likewise, if you have any CSS file use the same method –

<link rel="stylesheet" href="/projectcss/styles.css?v=01012021" />

Here in the link “href” property I have used an external CSS path and update the version with the date you can use any number of your choice and update the same each time you modify the CSS file.

If you refer to the file dynamically in server-side code use the same method and update the version in code like below –

@Html.IncludeVersionedJs("/scripts/jscustom.js?v=" + DateTime.Now.Ticks.toString());

Now when the user opens the site the new version of the JavaScript or CSS and been loaded in DOM and doesn’t need to hard refresh the site.

Conclusion

This is how you prevent the browser to cache JavaScript and CSS files. This technique is useful when you frequently deploy changes in the upper environment and your organization has a large user base.