subramani
subramani

Reputation:

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

Upvotes: 222

Views: 703945

Answers (23)

Kevin Hakanson
Kevin Hakanson

Reputation: 42200

Update: See location.reload() has no parameter for background on this nonstandard parameter and how Firefox is likely the only modern browser with support.


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.

Upvotes: 242

Sergey
Sergey

Reputation: 31

Most of the right answers are already mentioned in this topic. However I want to add link to the one article which is the best one I was able to read.

https://www.fastly.com/blog/clearing-cache-browser

As far as I can see the most suitable solution is:

POST in an iframe. Next is a small subtract from the suggested post:

=============

const ifr = document.createElement('iframe');
ifr.name = ifr.id = 'ifr_'+Date.now();
document.body.appendChild(ifr);
const form = document.createElement('form');
form.method = "POST";
form.target = ifr.name;
form.action = ‘/thing/stuck/in/cache’;
document.body.appendChild(form);
form.submit();

There’s a few obvious side effects: this will create a browser history entry, and is subject to the same issues of non-caching of the response. But it escapes the preflight requirements that exist for fetch, and since it’s a navigation, browsers that split caches will be clearing the right one.

This one almost nails it. Firefox will hold on to the stuck object for cross-origin resources but only for subsequent fetches. Every browser will invalidate the navigation cache for the object, both for same and cross origin resources.

==============================

We tried many things but that one works pretty well. The only issue is there you need to be able to bring this script somehow to end user page so you are able to reset cache. We were lucky in our particular case.

Upvotes: 3

brotatochip
brotatochip

Reputation: 31

I found a solution to this problem recently. In my case, I was trying to update an html element using javascript; I had been using XHR to update text based on data retrieved from a GET request. Although the XHR request happened frequently, the cached HTML data remained frustratingly the same.

Recently, I discovered a cache busting method in the fetch api. The fetch api replaces XHR, and it is super simple to use. Here's an example:

        async function updateHTMLElement(t) {
            let res = await fetch(url, {cache: "no-store"});
            if(res.ok){
                let myTxt = await res.text();
                document.getElementById('myElement').innerHTML = myTxt;
            }
        }

Notice that {cache: "no-store"} argument? This causes the browser to bust the cache for that element, so that new data gets loaded properly. My goodness, this was a godsend for me. I hope this is helpful for you, too.

Tangentially, to bust the cache for an image that gets updated on the server side, but keeps the same src attribute, the simplest and oldest method is to simply use Date.now(), and append that number as a url variable to the src attribute for that image. This works reliably for images, but not for HTML elements. But between these two techniques, you can update any info you need to now :-)

Upvotes: 3

yboussard
yboussard

Reputation: 245

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.length;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
      } 
   }
}

Upvotes: 8

Mafee7
Mafee7

Reputation: 47

Ref: https://developer.mozilla.org/en-US/docs/Web/API/Cache/delete

Cache.delete()

Method

Syntax:

cache.delete(request, {options}).then(function(found) {
  // your cache entry has been deleted if found
});

Upvotes: -3

raul7
raul7

Reputation: 201

I've solved this issue by using ETag

Etags are similar to fingerprints, and if the resource at a given URL changes, a new Etag value must be generated. A comparison of them can determine whether two representations of a resource are the same.

Upvotes: 0

Mygod
Mygod

Reputation: 2180

window.location.reload(true) seems to have been deprecated by the HTML5 standard. One way to do this without using query strings is to use the Clear-Site-Data header, which seems to being standardized.

Upvotes: 14

EMAM HASAN
EMAM HASAN

Reputation: 19

Cause browser cache same link, you should add a random number end of the url. new Date().getTime() generate a different number.

Just add new Date().getTime() end of link as like call

'https://stackoverflow.com/questions.php?' + new Date().getTime()

Output: https://stackoverflow.com/questions.php?1571737901173

Upvotes: 0

alfmonc
alfmonc

Reputation: 317

You can also disable browser caching with meta HTML tags just put html tags in the head section to avoid the web page to be cached while you are coding/testing and when you are done you can remove the meta tags.

(in the head section)

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0"/>

Refresh your page after pasting this in the head and should refresh the new javascript code too.

This link will give you other options if you need them http://cristian.sulea.net/blog/disable-browser-caching-with-meta-html-tags/

or you can just create a button like so

<button type="button" onclick="location.reload(true)">Refresh</button>

it refreshes and avoid caching but it will be there on your page till you finish testing, then you can take it off. Fist option is best I thing.

Upvotes: 4

Alexandre T.
Alexandre T.

Reputation: 3801

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>

Upvotes: 22

Luis H Cabrejo
Luis H Cabrejo

Reputation: 316

Maybe "clearing cache" is not as easy as it should be. Instead of clearing cache on my browsers, I realized that "touching" the file will actually change the date of the source file cached on the server (Tested on Edge, Chrome and Firefox) and most browsers will automatically download the most current fresh copy of whats on your server (code, graphics any multimedia too). I suggest you just copy the most current scripts on the server and "do the touch thing" solution before your program runs, so it will change the date of all your problem files to a most current date and time, then it downloads a fresh copy to your browser:

<?php
    touch('/www/control/file1.js');
    touch('/www/control/file2.js');
    touch('/www/control/file2.js');
?>

...the rest of your program...

It took me some time to resolve this issue (as many browsers act differently to different commands, but they all check time of files and compare to your downloaded copy in your browser, if different date and time, will do the refresh), If you can't go the supposed right way, there is always another usable and better solution to it. Best Regards and happy camping.

Upvotes: 4

John Balvin Arias
John Balvin Arias

Reputation: 2886

Please do not give incorrect information. Cache api is a diferent type of cache from http cache

HTTP cache is fired when the server sends the correct headers, you can't access with javasvipt.

Cache api in the other hand is fired when you want, it is usefull when working with service worker so you can intersect request and answer it from this type of cache see:ilustration 1 ilustration 2 course

You could use these techiques to have always a fresh content on your users:

  1. Use location.reload(true) this does not work for me, so I wouldn't recomend it.
  2. Use Cache api in order to save into the cache and intersect the request with service worker, be carefull with this one because if the server has sent the cache headers for the files you want to refresh, the browser will answer from the HTTP cache first, and if it does not find it, then it will go to the network, so you could end up with and old file
  3. Change the url from you stactics files, my recomendation is you should name it with the change of your files content, I use md5 and then convert it to string and url friendly, and the md5 will change with the content of the file, there you can freely send HTTP cache headers long enough

I would recomend the third one see

Upvotes: 4

user3573488
user3573488

Reputation: 70

If you are using php can do:

 <script src="js/myscript.js?rev=<?php echo time();?>"
    type="text/javascript"></script>

Upvotes: 3

Jay Shah
Jay Shah

Reputation: 3771

Cache.delete() can be used for new chrome, firefox and opera.

Upvotes: 1

Greg
Greg

Reputation: 321678

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:

myscript.123.js

or

myscript.js?updated=1234567890

Upvotes: 123

Apoorv
Apoorv

Reputation: 1389

window.parent.caches.delete("call")

close and open the browser after executing the code in console.

Upvotes: 0

Daniel
Daniel

Reputation: 1466

try using this

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

To this:

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

Upvotes: 7

Fabien M&#233;nager
Fabien M&#233;nager

Reputation: 140205

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

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

or

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

Upvotes: 11

Bryan
Bryan

Reputation: 1153

I had some troubles with the code suggested by yboussard. The inner j loop didn't work. Here is the modified code that I use with success.

function reloadScripts(toRefreshList/* list of js to be refresh */, key /* change this key every time you want force a refresh */) {
    var scripts = document.getElementsByTagName('script');
    for(var i = 0; i < scripts.length; i++) {
        var aScript = scripts[i];
        for(var j = 0; j < toRefreshList.length; j++) {
            var toRefresh = toRefreshList[j];
            if(aScript.src && (aScript.src.indexOf(toRefresh) > -1)) {
                new_src = aScript.src.replace(toRefresh, toRefresh + '?k=' + key);
                // console.log('Force refresh on cached script files. From: ' + aScript.src + ' to ' + new_src)
                aScript.src = new_src;
            }
        }
    }
}

Upvotes: 3

albanx
albanx

Reputation: 6335

or you can just read js file by server with file_get_contets and then put in echo in the header the js contents

Upvotes: 5

Justin Johnson
Justin Johnson

Reputation: 31300

Here's a snippet of what I'm using for my latest project.

From the controller:

if ( IS_DEV ) {
    $this->view->cacheBust = microtime(true);
} else {
    $this->view->cacheBust = file_exists($versionFile) 
        // The version file exists, encode it
        ? urlencode( file_get_contents($versionFile) )
        // Use today's year and week number to still have caching and busting 
        : date("YW");
}

From the view:

<script type="text/javascript" src="/javascript/somefile.js?v=<?= $this->cacheBust; ?>"></script>
<link rel="stylesheet" type="text/css" href="/css/layout.css?v=<?= $this->cacheBust; ?>">

Our publishing process generates a file with the revision number of the current build. This works by URL encoding that file and using that as a cache buster. As a fail-over, if that file doesn't exist, the year and week number are used so that caching still works, and it will be refreshed at least once a week.

Also, this provides cache busting for every page load while in the development environment so that developers don't have to worry with clearing the cache for any resources (javascript, css, ajax calls, etc).

Upvotes: 5

SpliFF
SpliFF

Reputation: 38976

I tend to version my framework then apply the version number to script and style paths

<cfset fw.version = '001' />
<script src="/scripts/#fw.version#/foo.js"/>

Upvotes: 1

Barry Gallagher
Barry Gallagher

Reputation: 6246

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.

Upvotes: 49

Related Questions