How to prevent caching of my Javascript file?

Bdfy picture Bdfy · Sep 14, 2011 · Viewed 241.3k times · Source

I have a simple html:

<html>
<body>
<head>
<meta charset="utf-8">
<meta http-equiv='cache-control' content='no-cache'>
<meta http-equiv='expires' content='0'>
<meta http-equiv='pragma' content='no-cache'>
<script src="test.js"></script>
</body>
</html>

In test.js I changed a Javascript function, but my browser is caching this file. How to disable cache for script src?

Answer

Curt picture Curt · Sep 14, 2011

Add a random query string to the src

You could either do this manually by incrementing the querystring each time you make a change:

<script src="test.js?version=1"></script>

Or if you are using a server side language, you could automatically generate this:

ASP.NET:

<script src="test.js?rndstr=<%= getRandomStr() %>"></script>

More info on cache-busting can be found here:

https://curtistimson.co.uk/post/front-end-dev/what-is-cache-busting/