Clear the cache in JavaScript

JavascriptCaching

Javascript Problem Overview


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.

https://stackoverflow.com/questions/118884/how-to-force-browser-to-reload-cached-css-js-files

https://stackoverflow.com/questions/32414/how-can-i-force-clients-to-refresh-javascript-files

https://stackoverflow.com/questions/12079631/dynamically-reload-local-javascript-source-json-data

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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

Solution 3 - Javascript

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 - Javascript

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 - Javascript

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>

Solution 6 - Javascript

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.

Solution 7 - Javascript

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
      } 
   }
}

Solution 8 - Javascript

try using this

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

To this:

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

Solution 9 - Javascript

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).

Solution 10 - Javascript

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

Solution 11 - Javascript

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.

Solution 12 - Javascript

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.

Solution 13 - Javascript

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

Solution 14 - Javascript

If you are using php can do:

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

Solution 15 - Javascript

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

Solution 16 - Javascript

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"/>

Solution 17 - Javascript

Solution 18 - Javascript

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 :-)

Solution 19 - Javascript

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.

Solution 20 - Javascript

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

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

Solution 21 - Javascript

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

Solution 22 - Javascript

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.

Solution 23 - Javascript

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
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsubramaniView Question on Stackoverflow
Solution 1 - JavascriptKevin HakansonView Answer on Stackoverflow
Solution 2 - JavascriptGregView Answer on Stackoverflow
Solution 3 - JavascriptBarry GallagherView Answer on Stackoverflow
Solution 4 - JavascriptAlexandre T.View Answer on Stackoverflow
Solution 5 - JavascriptFabien MénagerView Answer on Stackoverflow
Solution 6 - JavascriptMygodView Answer on Stackoverflow
Solution 7 - JavascriptyboussardView Answer on Stackoverflow
Solution 8 - JavascriptDanielView Answer on Stackoverflow
Solution 9 - JavascriptJustin JohnsonView Answer on Stackoverflow
Solution 10 - JavascriptalbanxView Answer on Stackoverflow
Solution 11 - JavascriptLuis H CabrejoView Answer on Stackoverflow
Solution 12 - JavascriptalfmoncView Answer on Stackoverflow
Solution 13 - JavascriptBryanView Answer on Stackoverflow
Solution 14 - Javascriptuser3573488View Answer on Stackoverflow
Solution 15 - JavascriptJohn Balvin AriasView Answer on Stackoverflow
Solution 16 - JavascriptSpliFFView Answer on Stackoverflow
Solution 17 - JavascriptJay ShahView Answer on Stackoverflow
Solution 18 - JavascriptbrotatochipView Answer on Stackoverflow
Solution 19 - JavascriptSergeyView Answer on Stackoverflow
Solution 20 - JavascriptApoorvView Answer on Stackoverflow
Solution 21 - JavascriptEMAM HASANView Answer on Stackoverflow
Solution 22 - Javascriptraul7View Answer on Stackoverflow
Solution 23 - JavascriptMafee7View Answer on Stackoverflow