Clear the cache in JavaScript

Clear the cache in JavaScript

How do I clear a browsers cache with JavaScript?
We deployed the latest JavaScript code but we are unable to get the latest JavaScript code.
Editorial Note: This question is semi-duplicated in the following places, and the answer in the first of the following questions is probably the best. This accepted answer is no longer the ideal solution.
How to force browser to reload cached CSS/JS files?
How can I force clients to refresh JavaScript files?
Dynamically reload local Javascript source / json data


Solution 1:

You can call window.location.reload(true) to reload the current page. It will ignore any cached items and retrieve new copies of the page, css, images, JavaScript, etc from the server. This doesn’t clear the whole cache, but has the effect of clearing the cache for the page you are on.

However, your best strategy is to version the path or filename as mentioned in various other answers. In addition, see Revving Filenames: don’t use querystring for reasons not to use ?v=n as your versioning scheme.

Related:  javascript Rich Text Editors

Solution 2:

You can’t clear the cache with javascript.
A common way is to append the revision number or last updated timestamp to the file, like this:




Solution 3:

Try changing the JavaScript file’s src? From this:

<script language="JavaScript" src="js/myscript.js"></script>

To this:

<script language="JavaScript" src="js/myscript.js?n=1"></script>

This method should force your browser to load a new copy of the JS file.

Solution 4:

Other than caching every hour, or every week, you may cache according to file data.

Example (in PHP):

<script src="js/my_script.js?v=<?=md5_file('js/my_script.js')?>"></script>

or even use file modification time:

<script src="js/my_script.js?v=<?=filemtime('js/my_script.js')?>"></script>

Solution 5:

You can also force the code to be reloaded every hour, like this, in PHP :

echo '<script language="JavaScript" src="js/myscript.js?token='.date('YmdH').'">';


<script type="text/javascript" src="js/myscript.js?v=<?php echo date('YmdHis'); ?>"></script>

Solution 6:

put this at the end of your template :

var scripts =  document.getElementsByTagName('script');
var torefreshs = ['myscript.js', 'myscript2.js'] ; // list of js to be refresh
var key = 1; // change this key every time you want force a refresh
for(var i=0;i<scripts.length;i++){ 
   for(var j=0;j<torefreshs;j++){ 
      if(scripts[i].src && (scripts[i].src.indexOf(torefreshs[j]) > -1)){
        new_src = scripts[i].src.replace(torefreshs[j],torefreshs[j] + 'k=' + key );
        scripts[i].src = new_src; // change src in order to refresh js