How can I refresh a page with jQuery?

JavascriptJqueryRefreshReload

Javascript Problem Overview


How can I refresh a page with jQuery?

Javascript Solutions


Solution 1 - Javascript

Use location.reload():

$('#something').click(function() {
    location.reload();
});

The reload() function takes an optional parameter that can be set to true to force a reload from the server rather than the cache. The parameter defaults to false, so by default the page may reload from the browser's cache.

Solution 2 - Javascript

There are multiple unlimited ways to refresh a page with JavaScript:

  1. location.reload()

  2. history.go(0)

  3. location.href = location.href

  4. location.href = location.pathname

  5. location.replace(location.pathname)

  6. location.reload(false)

    > If we needed to pull the document from the web-server again (such as where the document contents change dynamically) we would pass the argument as true.

You can continue the list being creative:

  • window.location = window.location
  • window.self.window.self.window.window.location = window.location
  • ...and other 534 ways

var methods = [
  "location.reload()",
  "history.go(0)",
  "location.href = location.href",
  "location.href = location.pathname",
  "location.replace(location.pathname)",
  "location.reload(false)"
];

var $body = $("body");
for (var i = 0; i < methods.length; ++i) {
  (function(cMethod) {
    $body.append($("<button>", {
      text: cMethod
    }).on("click", function() {
      eval(cMethod); // don't blame me for using eval
    }));
  })(methods[i]);
}

button {
  background: #2ecc71;
  border: 0;
  color: white;
  font-weight: bold;
  font-family: "Monaco", monospace;
  padding: 10px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.5s ease;
  margin: 2px;
}
button:hover {
  background: #27ae60;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Solution 3 - Javascript

This should work on all browsers even without jQuery:

location.reload();

Solution 4 - Javascript

Lots of ways will work, I suppose:

  • window.location.reload();
  • history.go(0);
  • window.location.href=window.location.href;

Solution 5 - Javascript

To reload a page with jQuery, do:

$.ajax({
    url: "",
    context: document.body,
    success: function(s,x){
        $(this).html(s);
    }
});

The approach here that I used was Ajax jQuery. I tested it on Chrome 13. Then I put the code in the handler that will trigger the reload. The URL is "", which means this page.

Solution 6 - Javascript

If the current page was loaded by a POST request, you may want to use

window.location = window.location.pathname;

instead of

window.location.reload();

because window.location.reload() will prompt for confirmation if called on a page that was loaded by a POST request.

Solution 7 - Javascript

The question should be,

How to refresh a page with JavaScript

window.location.href = window.location.href; //This is a possibility
window.location.reload(); //Another possiblity
history.go(0); //And another

You're spoiled for choice.

Solution 8 - Javascript

You may want to use

location.reload(forceGet)

forceGet is a boolean and optional.

The default is false which reloads the page from the cache.

Set this parameter to true if you want to force the browser to get the page from the server to get rid of the cache as well.

Or just

location.reload()

if you want quick and easy with caching.

Solution 9 - Javascript

Three approaches with different cache-related behaviours:

  • location.reload(true)

    In browsers that implement the forcedReload parameter of location.reload(), reloads by fetching a fresh copy of the page and all of its resources (scripts, stylesheets, images, etc.). Will not serve any resources from the cache - gets fresh copies from the server without sending any if-modified-since or if-none-match headers in the request.

    Equivalent to the user doing a "hard reload" in browsers where that's possible.

    Note that passing true to location.reload() is supported in Firefox (see MDN) and Internet Explorer (see MSDN) but is not supported universally and is not part of the W3 HTML 5 spec, nor the W3 draft HTML 5.1 spec, nor the WHATWG HTML Living Standard.

    In unsupporting browsers, like Google Chrome, location.reload(true) behaves the same as location.reload().

  • location.reload() or location.reload(false)

    Reloads the page, fetching a fresh, non-cached copy of the page HTML itself, and performing RFC 7234 revalidation requests for any resources (like scripts) that the browser has cached, even if they are fresh are RFC 7234 permits the browser to serve them without revalidation.

    Exactly how the browser should utilise its cache when performing a location.reload() call isn't specified or documented as far as I can tell; I determined the behaviour above by experimentation.

    This is equivalent to the user simply pressing the "refresh" button in their browser.

  • location = location (or infinitely many other possible techniques that involve assigning to location or to its properties)

    Only works if the page's URL doesn't contain a fragid/hashbang!

    Reloads the page without refetching or revalidating any fresh resources from the cache. If the page's HTML itself is fresh, this will reload the page without performing any HTTP requests at all.

    This is equivalent (from a caching perspective) to the user opening the page in a new tab.

    However, if the page's URL contains a hash, this will have no effect.

    Again, the caching behaviour here is unspecified as far as I know; I determined it by testing.

So, in summary, you want to use:

  • location = location for maximum use of the cache, as long as the page doesn't have a hash in its URL, in which case this won't work

  • location.reload(true) to fetch new copies of all resources without revalidating (although it's not universally supported and will behave no differently to location.reload() in some browsers, like Chrome)

  • location.reload() to faithfully reproduce the effect of the user clicking the 'refresh' button.

Solution 10 - Javascript

window.location.reload() will reload from the server and will load all your data, scripts, images, etc. again.

So if you just want to refresh the HTML, the window.location = document.URL will return much quicker and with less traffic. But it will not reload the page if there is a hash (#) in the URL.

Solution 11 - Javascript

The jQuery Load function can also perform a page refresh:

$('body').load('views/file.html', function () {
    $(this).fadeIn(5000);
});

Solution 12 - Javascript

As the question is generic, let's try to sum up possible solutions for the answer:

Simple plain JavaScript Solution:

The easiest way is a one line solution placed in an appropriate way:

location.reload();

What many people are missing here, because they hope to get some "points" is that the reload() function itself offers a Boolean as a parameter (details: [https://developer.mozilla.org/en-US/docs/Web/API/Location/reload][1]).

> The Location.reload() method reloads the resource from the current > URL. Its optional unique parameter is a Boolean, which, when it is > true, causes the page to always be reloaded from the server. If it is > false or not specified, the browser may reload the page from its > cache.

This means there are two ways:

Solution1: Force reloading the current page from the server

location.reload(true);

Solution2: Reloading from cache or server (based on browser and your config)

location.reload(false);
location.reload();

And if you want to combine it with jQuery an listening to an event, I would recommend using the ".on()" method instead of ".click" or other event wrappers, e.g. a more proper solution would be:

$('#reloadIt').on('eventXyZ', function() {
    location.reload(true);
});

[1]: https://developer.mozilla.org/en-US/docs/Web/API/Location/reload "Reload MDN"

Solution 13 - Javascript

Here is a solution that asynchronously reloads a page using jQuery. It avoids the flicker caused by window.location = window.location. This example shows a page that reloads continuously, as in a dashboard. It is battle-tested and is running on an information display TV in Times Square.

<!DOCTYPE html>
<html lang="en">
  <head>
    ...
    <meta http-equiv="refresh" content="300">
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
    <script>
    function refresh() {
      $.ajax({
        url: "",
        dataType: "text",
        success: function(html) {
          $('#fu').replaceWith($.parseHTML(html));
          setTimeout(refresh,2000);
        }
      });
    }
    refresh();
    </script>
  </head>
  <body>
    <div id="fu">
      ...
    </div>
  </body>
</html>

Notes:

Solution 14 - Javascript

I found

window.location.href = "";

or

window.location.href = null;

also makes a page refresh.

This makes it very much easier to reload the page removing any hash. This is very nice when I am using AngularJS in the iOS simulator, so that I don't have to rerun the app.

Solution 15 - Javascript

You can use JavaScript location.reload() method. This method accepts a boolean parameter. true or false. If the parameter is true; the page always reloaded from the server. If it is false; which is the default or with empty parameter browser reload the page from it's cache.

With true parameter

<button type="button" onclick="location.reload(true);">Reload page</button>

With default/ false parameter

 <button type="button" onclick="location.reload();">Reload page</button>

Using jquery

<button id="Reloadpage">Reload page</button>
<script type="text/javascript">
	$('#Reloadpage').click(function() {
		location.reload();
	}); 
</script>

Solution 16 - Javascript

You don't need anything from jQuery, to reload a page using pure JavaScript, just use reload function on location property like this:

window.location.reload();

By default, this will reload the page using the browser cache (if exists)...

If you'd like to do force reload the page, just pass a true value to reload method like below...

window.location.reload(true);

Also if you are already in window scope, you can get rid of window and do:

location.reload();

Solution 17 - Javascript

use

location.reload();

or

window.location.reload();

Solution 18 - Javascript

<i id="refresh" class="fa fa-refresh" aria-hidden="true"></i>

<script>
$(document).on('click','#refresh',function(){
   location.reload(true);
});
</script>

Solution 19 - Javascript

you may need to use

 location.reload()

or also may need to use

location.reload(forceGet)

forceGet is a boolean and optional.

Set this parameter to true if you want to force the browser to take the page from the server to receive rid of the cache as well

Solution 20 - Javascript

Use onclick="return location.reload();" within the button tag.

<button id="refersh-page" name="refersh-page" type="button" onclick="return location.reload();">Refesh Page</button>

Solution 21 - Javascript

If you are using jQuery and want to refresh, then try adding your jQuery in a javascript function:

I wanted to hide an iframe from a page when clicking oh an h3, for me it worked but I wasn't able to click the item that allowed me to view the iframe to begin with unless I refreshed the browser manually...not ideal.

I tried the following:

var hide = () => {
    $("#frame").hide();//jQuery
    location.reload(true);//javascript
};

Mixing plain Jane javascript with your jQuery should work.

// code where hide (where location.reload was used)function was integrated, below    
    iFrameInsert = () => {
        var file = `Fe1FVoW0Nt4`;
        $("#frame").html(`<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/${file}\" frameborder=\"0\" allow=\"autoplay; encrypted-media\" allowfullscreen></iframe><h3>Close Player</h3>`);
        $("h3").enter code hereclick(hide);
}

// View Player 
$("#id-to-be-clicked").click(iFrameInsert);

Solution 22 - Javascript

All the answers here are good. Since the question specifies about reloading the page with [tag:jQuery], I just thought adding something more for future readers.

>jQuery is a cross-platform JavaScript library designed to simplify the client-side scripting of HTML. > >~ Wikipedia ~

So you'll understand that the foundation of [tag:jQuery], or [tag:jQuery] is based on [tag:JavaScript]. So going with pure [tag:JavaScript] is way better when it comes to simple things.

But if you need a [tag:jQuery] solution, here's one.

$(location).attr('href', '');

Solution 23 - Javascript

There are many ways to reload the current pages, but somehow using those approaches you can see page updated but not with few cache values will be there, so overcome that issue or if you wish to make hard requests then use the below code.

    location.reload(true);
    //Here, it will make a hard request or reload the current page and clear the cache as well.
    
    
    location.reload(false); OR location.reload();
    //It can be reload the page with cache

Solution 24 - Javascript

You can write it in two ways. 1st is the standard way of reloading the page also called as simple refresh

location.reload(); //simple refresh

And another is called the hard refresh. Here you pass the boolean expression and set it to true. This will reload the page destroying the older cache and displaying the contents from scratch.

location.reload(true);//hard refresh

Solution 25 - Javascript

This works for me.

function reload(){
    location.reload(true);
}

Solution 26 - Javascript

Simple Javascript Solution:

 location = location; 

<button onClick="location = location;">Reload</button>

Solution 27 - Javascript

Probably shortest (12 chars) - use history

history.go()

Solution 28 - Javascript

$(document).on("click", "#refresh_btn", function(event) 
{
     window.location.replace(window.location.href);
});

Solution 29 - Javascript

It is shortest in JavaScript.

window.location = '';

Solution 30 - Javascript

Y'all may need to use

    location.reload(forceGet)

forceGet is a boolean and optional.

The default is false, which reloads the page of the cache.

Solution 31 - Javascript

Here are some lines of code you can use to reload the page using jQuery.

It uses the jQuery wrapper and extracts the native dom element.

Use this if you just want a jQuery feeling on your code and you don't care about speed/performance of the code.

Just pick from 1 to 10 that suits your needs or add some more based on the pattern and answers before this.

<script>
  $(location)[0].reload(); //1
  $(location).get(0).reload(); //2
  $(window)[0].location.reload(); //3
  $(window).get(0).location.reload(); //4
  $(window)[0].$(location)[0].reload(); //5
  $(window).get(0).$(location)[0].reload(); //6
  $(window)[0].$(location).get(0).reload(); //7
  $(window).get(0).$(location).get(0).reload(); //8
  $(location)[0].href = ''; //9
  $(location).get(0).href = ''; //10
  //... and many other more just follow the pattern.
</script>

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
QuestionlucaView Question on Stackoverflow
Solution 1 - JavascriptRoyView Answer on Stackoverflow
Solution 2 - JavascriptIonică BizăuView Answer on Stackoverflow
Solution 3 - JavascriptThorbenView Answer on Stackoverflow
Solution 4 - JavascriptDavidView Answer on Stackoverflow
Solution 5 - JavascriptPeterView Answer on Stackoverflow
Solution 6 - JavascriptSumairIrshadView Answer on Stackoverflow
Solution 7 - JavascriptJohnPView Answer on Stackoverflow
Solution 8 - JavascriptPinchView Answer on Stackoverflow
Solution 9 - JavascriptMark AmeryView Answer on Stackoverflow
Solution 10 - Javascriptuser762330View Answer on Stackoverflow
Solution 11 - JavascriptSuleman MirzaView Answer on Stackoverflow
Solution 12 - JavascriptFer ToView Answer on Stackoverflow
Solution 13 - JavascriptWilliam EntrikenView Answer on Stackoverflow
Solution 14 - JavascriptMujah MaskeyView Answer on Stackoverflow
Solution 15 - JavascriptPoorna Senani GamageView Answer on Stackoverflow
Solution 16 - JavascriptAlirezaView Answer on Stackoverflow
Solution 17 - JavascriptH.OstwalView Answer on Stackoverflow
Solution 18 - Javascriptankit singhView Answer on Stackoverflow
Solution 19 - JavascriptTharindu LakshanView Answer on Stackoverflow
Solution 20 - JavascriptFrankView Answer on Stackoverflow
Solution 21 - JavascriptJ. MorenoView Answer on Stackoverflow
Solution 22 - JavascriptRoshana PitigalaView Answer on Stackoverflow
Solution 23 - JavascriptankitkanojiaView Answer on Stackoverflow
Solution 24 - JavascriptinfomasudView Answer on Stackoverflow
Solution 25 - JavascriptPri NceView Answer on Stackoverflow
Solution 26 - JavascriptUnmitigatedView Answer on Stackoverflow
Solution 27 - JavascriptKamil KiełczewskiView Answer on Stackoverflow
Solution 28 - JavascriptAnkush KumarView Answer on Stackoverflow
Solution 29 - JavascriptNa NonthasenView Answer on Stackoverflow
Solution 30 - Javascriptuser15255379View Answer on Stackoverflow
Solution 31 - JavascriptdcanguloView Answer on Stackoverflow