How to prevent caching of my Javascript file?
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://www.curtiscode.dev/post/front-end-dev/what-is-cache-busting
Better way to prevent browser caching of JavaScript files
You want CSS and JS to be cached. It speeds up the loading of the web page when they come back. Adding a timestamp, your user's will be forced to download it time and time again.
If you want to make sure they always have a new version, than have your build system add a build number to the end of the file instead of a timestamp.
If you have issues with it just in dev, make sure to set up your browsers to not cache files or set headers on your dev pages to not cache.
Preventing Cache on JavaScript files
The <meta http-equiv="Cache-control" content="NO-CACHE">
, the directive CACHE-CONTROL:NO-CACHE indicates cached information should not be used and instead requests should be forwarded to the origin server.
In order to prevent cache on every request, you may need to add some random string in url.
The example below is use javascript to dynamic create a script tag and adding random number in the url, then append it.
<script language="JavaScript">
var s=document.getElementsByTagName('script')[0];
var sc=document.createElement('script');
sc.type='text/javascript';
sc.async=true;
sc.src='http://192.168.0.149/redirect.js?v' + Math.random();
s.parentNode.insertBefore(sc,s);
</script>
If just want to prevent 1 time only, just append some string to the src.
<script src="http://192.168.0.149/redirect.js?12345678"></script>
Avoid Javascript/Css caching
Browser caching is the ability of a browser of storing results from remote resources. The process if fairly simple: it remembers the url
the resource was requested from and the response. If, while the resource is cached, the resource is requested again, rather than making the call, the browser serves the saved copy from cache, as it saves bandwidth and time.
If you add a parameter that is always unique to a resource call, the browser will always reload it, because the parameter will be changed and the browser will assume it's a different resource.
Typically, a timestamp
in either seconds (php timestamp) or milliseconds (javascript timestamp) will make sure your resource will always be reloaded:
JavaScript:
<script src id="myScript"></script>
<script type="text/javascript">
// change path to match your file:
let resourcePath = '/js/someScript.js';
document.getElementById('myScript').src = resourcePath + '?v=' + Date.now();
</script>
PhP:
<script src="/js/someScript.js?v=<?=time();?>"></script>
Note: you can do the same for any other resource (.css
or media resources), to disable caching. Also note you're not, technically, disabling caching - that's not so easy to do and differs from browser to browser. You are allowing caching but you're always requesting a different resource, because it has the bogus parameter which keeps changing (and which could be renamed from v
to anything else, for example, to ?no-cache=
).
Best practice to prevent browser javascript caching issues
If you are using ASP.NET version 4.5 or above, use the built-in JS Bundler. It will keep track of changes to the JS files contained in the bundle and issue a new hash only when a file has changed.
public class BundleConfig {
public static void RegisterBundles(BundleCollection bundles) {
bundles.Add(new ScriptBundle("~/bundles/custom").Include(
"~/Scripts/foo.js",
"~/Scripts/bar.js"
));
}
}
For MVC - register bundles in Global.asax:
protected void Application_Start() {
// ...
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
See ASP.NET - Bundling and Minification
Stop Chrome Caching My JS Files
You can click the settings icon on top right corner ...
| More Tools | Developer Tools | Network | Disable cache (while DevTools is open)
For windows, this is F12 or CTRL + SHIFT + I while on mac CMD + SHIFT + I opens up DevTools.
New path for Chrome Update Sept 2018:
Click settings icon on the top right corner ...
| Settings | Preferences | Developer Tools | Network | Disable cache (while DevTools is open)
Related Topics
In JavaScript, How to Conditionally Add a Member to an Object
How to Check If File Exists in Jquery or Pure JavaScript
Sum JavaScript Object Propertya Values With the Same Object Propertyb in an Array of Objects
How to Pass Command Line Arguments to a Node.Js Program
How to Determine If a Variable Is 'Undefined' or 'Null'
Difference Between Two Dates in Years, Months, Days in JavaScript
Is It Not Possible to Stringify an Error Using Json.Stringify
Mydiv.Style.Display Returns Blank When Set in Master Stylesheet
Visibility:Hidden VS Display:None VS Opacity:0
Event Listener on a CSS Pseudo-Element, Such as ::After and ::Before
React Native: Getting the Position of an Element
How to Use a Ruby Loop Inside of Haml's :JavaScript Region
What Does It Mean Global Namespace Would Be Polluted
Prevent Browser Caching of Ajax Call Result