183

I want to reload a page using JavaScript but I want to clear cache too, so on page refresh the page has latest versions of everything from server.
Other browsers except IE are not getting latest content.

Any solution for IE9?

YakovL
  • 7,557
  • 12
  • 62
  • 102
coure2011
  • 40,286
  • 83
  • 216
  • 349
  • 6
    ugly things may happen as users sit behind proxies. To be sure page reloads, just add a randomized val to your url. – Teson Apr 19 '11 at 21:15
  • 1
    `window.location.href = window.location.href` – Ivan Jul 16 '19 at 11:15
  • 1)I saved a HTML page with DIV - MainDIV with many DIVS inside it. 2)When I assign HTML to this DIV how do I clear whatever is in the DIV and assigned the saved Div value? 3)Do you have an idea on how to solve this requirement? – RedBottleSanitizer Oct 22 '21 at 16:37

5 Answers5

268

reload() is supposed to accept an argument which tells it to do a hard reload, ie, ignoring the cache:

location.reload(true);

I can't vouch for its reliability, you may want to investigate this further.


Edit (2021): the parameter was never standardised and has been deprecated and removed in more modern browsers. Adding a comment every quarter describing this fact will not help.

Christian
  • 27,509
  • 17
  • 111
  • 155
  • does it work for android webkit browser? – prongs Mar 29 '12 at 07:44
  • @prongs I don't see why it shouldn't. Of course, I don't have an Android-based webkit to test it on... – Christian Mar 29 '12 at 14:40
  • 29
    works in IE and FF but not in Chrome, Safari. Anyone know how to make this happen in Chrome, Safari? – testpattern Oct 30 '12 at 13:31
  • Should work in FF and Chrome, look at the supported browsers at the bottom https://developer.mozilla.org/en-US/docs/Web/API/Location.reload - but they weren't specific on which versions of IE, I'd say don't expect it to work for IE9 and lower: http://social.msdn.microsoft.com/Forums/ie/en-US/de9c5845-5fac-4fda-9b2d-2b435e805abd/windowlocationreloadtrue-is-not-working-in-ie-9?forum=ieextensiondevelopment – Clarence Liu Apr 03 '14 at 07:48
  • 2
    Will this force a reload of referenced files, too? (like JS and CSS files and images embedded in the page?) – wotanii Nov 23 '15 at 10:19
  • Yes, that's the point of having this method skip the cache. – Christian Nov 23 '15 at 11:09
  • 3
    I am working on an AngularJs app, I use window.location.reload(true); but it is still using the cached JS script. – klode Apr 04 '16 at 21:19
  • I am also working on an Angular app (1.4.9) and its the only solution that works. I just need to add a boolean to the current user's object that is set to false after reload to avoid reloading at each route. – vonwolf Jun 08 '16 at 14:52
  • Where should `location.reload(true)` be placed in the code? – Fed May 21 '17 at 16:03
  • @FedericoCapaldo I cannot tell you that, it's up to you.. – Christian May 21 '17 at 23:19
  • more info u could find in https://developer.mozilla.org/en-US/docs/Web/API/Location/reload – Aleksandr Golovatyi May 15 '18 at 08:41
  • 12
    this worked for me in chrome `window.location.href = window.location.href` – Ivan Jul 16 '19 at 11:14
  • @GspIvan Many thanks, worked for me and solved my problem – abdelrhman raafat Mar 08 '20 at 07:41
  • worked for me with firefox, thanks. – jumptiger13 Oct 01 '20 at 19:34
  • 1
    the forceReload flag was deprecated. https://stackoverflow.com/questions/55127650/location-reloadtrue-is-deprecated – Guy Jul 13 '21 at 01:30
  • location.reload() has no parameter! Any parameter you specify in a location.reload() call will be ignored and have no effect of any kind. You can read more about it here: https://developer.mozilla.org/en-US/docs/Web/API/Location/reload – Antonio Aug 17 '21 at 10:20
  • 5
    @Antonio when the answer was written (**10 years ago**) it used to work. It has since been deprecated and removed. The mozilla documentation is actually partially wrong - it's been documented for MSIE, for example: https://web.archive.org/web/20140619064920/http://blogs.msdn.com/b/ieinternals/archive/2010/07/08/technical-information-about-conditional-http-requests-and-the-refresh-button.aspx (see `bReloadSource`) – Christian Aug 18 '21 at 07:10
  • 1
    You can change the URL with a timestamp as a search parameter and the browser will force a new fetch. `window.location.href = window.location.origin + window.location.pathname + window.location.search + (window.location.search ? '&' : '?') + 'reloadTime=' + Date.now().toString() + window.location.hash;` – ShortFuse Jan 28 '22 at 23:51
  • https://developer.mozilla.org/en-US/docs/Web/API/Location/reload#location.reload_has_no_parameter – Tharanga Apr 20 '22 at 15:04
  • @Tharanga can you please read the comments first? This has been discussed twice already. – Christian Apr 22 '22 at 08:02
  • @ShortFuse does this refetch affect all other locations or just the current location? If not, how does one archive one for all locations? – Dennis Henry Sep 16 '22 at 20:42
  • @DennisHenry it only affects the current location - any cached resources used by that location remain cached. This is why some build systems add a version parameter to all generated resources (or rename the resources). This also means you can use the same thing yourself: assuming you have an index.php that receives a `$_GET['v']`; simply define your resources with `href="style.css?v== min(max((int)$_GET['v'], 0), 5) ?>"` (5 would be your latest version; to decrease DDOS potential - you can do this validation once at the beginning). – Christian Sep 17 '22 at 22:34
  • @DennisHenry Only the current URL. I had a more detailed answer at https://stackoverflow.com/a/70901317/1426683 that shows how to apply it to all CSS. Adding a param to force hard reload is a form of what's called "Cache Busting": https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching#cache_busting – ShortFuse Sep 20 '22 at 16:10
79

You can do this a few ways. One, simply add this meta tag to your head:

<meta http-equiv="Cache-control" content="no-cache">

If you want to remove the document from cache, expires meta tag should work to delete it by setting its content attribute to -1 like so:

<meta http-equiv="Expires" content="-1">

http://www.metatags.org/meta_http_equiv_cache_control

Also, IE should give you the latest content for the main page. If you are having issues with external documents, like CSS and JS, add a dummy param at the end of your URLs with the current time in milliseconds so that it's never the same. This way IE, and other browsers, will always serve you the latest version. Here is an example:

<script src="mysite.com/js/myscript.js?12345">

UPDATE 1

After reading the comments I realize you wanted to programmatically erase the cache and not every time. What you could do is have a function in JS like:

eraseCache(){
  window.location = window.location.href+'?eraseCache=true';
}

Then, in PHP let's say, you do something like this:

<head>
<?php
    if (isset($_GET['eraseCache'])) {
        echo '<meta http-equiv="Cache-control" content="no-cache">';
        echo '<meta http-equiv="Expires" content="-1">';
        $cache = '?' . time();
    }
?>
<!-- ... other head HTML -->
<script src="mysite.com/js/script.js<?= $cache ?>"
</head>

This isn't tested, but should work. Basically, your JS function, if invoked, will reload the page, but adds a GET param to the end of the URL. Your site would then have some back-end code that looks for this param. If it exists, it adds the meta tags and a cache variable that contains a timestamp and appends it to the scripts and CSS that you are having caching issues with.

UPDATE 2

The meta tag indeed won't erase the cache on page load. So, technically you would need to run the eraseCache function in JS, once the page loads, you would need to load it again for the changes to take place. You should be able to fix this with your server side language. You could run the same eraseCache JS function, but instead of adding the meta tags, you need to add HTTP Cache headers:

<?php
    header("Cache-Control: no-cache, must-revalidate");
    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
?>
<!-- Here you'd start your page... -->

This method works immediately without the need for page reload because it erases the cache before the page loads and also before anything is run.

Wolverine
  • 1,712
  • 1
  • 15
  • 18
Oscar Godson
  • 31,662
  • 41
  • 121
  • 201
  • 6
    Correct me if I am wrong, but the meta cache-control tag will prevent the caching of the page being loaded. It will not clear the cache already saved in the clients browser. – Keylan Apr 19 '11 at 20:34
  • 2
    Also, adding the time in milliseconds to the end of your src attribute will never allow that javascript file to be cached... which is not advisable. I took it from the question that coure06 wants to be able to clear the browser's cache by request - not permanently insure the file will never be cached. Perhaps a combined solution is to make a link to the same page with an included GET param that will force the javascript includes to have the current time appended. – Keylan Apr 19 '11 at 20:38
  • 1
    Just going to keep adding comments as I think new things up apparently. Adding the milliseconds to the file path based on certain events would not work as easily imagined, as after this is done once - the file path can never go back to just myscript.js because the browser would just switch back to the cached file. – Keylan Apr 19 '11 at 20:44
  • Check out my updated answer. The Expires meta tag should fix that. And using your GET idea, i updated the script. It's not tested, but i think it should work... – Oscar Godson Apr 19 '11 at 21:10
  • I understand the direction you are headed - but once again the problem is that even the Expires meta tag will only affect the current page being loaded, and will not touch anything already cached by the browser. – Keylan Apr 19 '11 at 21:16
  • 1
    I dont think I understand. The expires will make the current page's cache expire. It should erase it all and IE will grab everything fresh. He isn't saying he wants to erase the user's cache for every site and every page, just for the page being reloaded. – Oscar Godson Apr 19 '11 at 21:21
  • http://www.mnot.net/cache_docs/#META Describes a few issues with using HTML Meta Tags to control cache. But assume what you say works and think about the consequences - the new page reloads with the HTML expires META tag... now what? The user has to reload the page once again to make the browser request the now marked expired javascript files? – Keylan Apr 19 '11 at 21:35
  • I see, i see. Good point, OK, updating my post again, in 1 second... – Oscar Godson Apr 19 '11 at 22:45
  • 1
    For "Update 1": won't work, because page.html and page.html?eraseCache=true are separate cache entries (the cache is querystring-aware). "Update 2" won't work either, because you're serving your "erase the cache" headers *from the server*, but the whole problem you're trying to solve is that the page is being served from the cache and isn't hitting the server! – Doin Sep 25 '21 at 00:10
11

i had this problem and i solved it using javascript

 location.reload(true);

you may also use

window.history.forward(1);

to stop the browser back button after user logs out of the application.

yousef
  • 1,240
  • 12
  • 13
7

In my case reload() doesn't work because the asp.net controls behavior. So, to solve this issue I've used this approach, despite seems a work around.

self.clear = function () {
    //location.reload(true); Doesn't work to IE neither Firefox;
    //also, hash tags must be removed or no postback will occur.
    window.location.href = window.location.href.replace(/#.*$/, '');
};
Rodrigo
  • 751
  • 11
  • 16
5

I wrote this javascript script and included it in the header (before anything loads). It seems to work. If the page was loaded more than one hour ago or the situation is undefined it will reload everything from server. The time of one hour = 3600000 milliseconds can be changed in the following line: if(alter > 3600000)

With regards, Birke

<script type="text/javascript">
//<![CDATA[
function zeit()
{
    if(document.cookie)
    {
        a = document.cookie;
        cookiewert = "";
        while(a.length > 0)
        {
            cookiename = a.substring(0,a.indexOf('='));
            if(cookiename == "zeitstempel")
            {
                cookiewert = a.substring(a.indexOf('=')+1,a.indexOf(';'));
                break;
            }
            a = a.substring(a.indexOf(cookiewert)+cookiewert.length+1,a.length);
        }
        if(cookiewert.length > 0)
        {
            alter = new Date().getTime() - cookiewert;

            if(alter > 3600000)
            {   
                document.cookie = "zeitstempel=" + new Date().getTime() + ";";
                location.reload(true);
            }
            else
            {
                return;
            }
        }
        else
        {
            document.cookie = "zeitstempel=" + new Date().getTime() + ";";
            location.reload(true);
        }
    }
    else
    {
        document.cookie = "zeitstempel=" + new Date().getTime() + ";";
        location.reload(true);
    }
}
zeit();
//]]>
</script>
Birke
  • 51
  • 1
  • 2