How do I refresh a page using JavaScript?
Use location.reload().
For example, to reload whenever an element with id="something" is clicked:
$('#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.
There are multiple unlimited ways to refresh a page with JavaScript:
location.reload()
history.go(0)
location.href = location.href
location.href = location.pathname
location.replace(location.pathname)
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>
This works on all browsers:
location.reload();
Lots of ways will work, I suppose:
window.location.reload();
history.go(0);
window.location.href=window.location.href;
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.
Edit2: The original question was "How to reload a page with JQUERY"! Downvoters take note.
Edit: Unfortunately, I'll have to take down this answer very soon because, the question has changed and the user seemed to not be very clear on what they were asking. Some users have commented that refreshing is different from reloading a page; See the revisions to this question [https://stackoverflow.com/posts/5404839/revisions] As far as I can tell, from the original question which was around refreshing a page with AJAX which is ASYNCHRONOUS ..., refreshing a page should imply getting new and updated content to the page. Anyway, this answer will soon go away./
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.
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.
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.
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.
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.
The jQuery Load function can also perform a page refresh:
$('body').load('views/file.html', function () {
$(this).fadeIn(5000);
});
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).
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);
});
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:
Using $.ajax directly like $.get('',function(data){$(document.body).html(data)}) causes css/js files to get cache-busted, even if you use cache: true, that's why we use parseHTML
parseHTML will NOT find a body tag so your whole body needs to go in an extra div, I hope this nugget of knowledge helps you one day, you can guess how we chose the id for that div
Use http-equiv="refresh" just in case something goes wrong with javascript/server hiccup, then the page will STILL reload without you getting a phone call
This approach probably leaks memory somehow, the http-equiv refresh fixes that
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.
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>
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();
use
location.reload();
or
window.location.reload();
<i id="refresh" class="fa fa-refresh" aria-hidden="true"></i>
<script>
$(document).on('click','#refresh',function(){
location.reload(true);
});
</script>
This works for me.
function reload(){
location.reload(true);
}
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>
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);
All the answers here are good. Since the question specifies about reloading the page with 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 jquery, or jquery is based on javascript. So going with pure javascript is way better when it comes to simple things.
But if you need a jquery solution, here's one.
$(location).attr('href', '');
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
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
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
Simple Javascript Solution:
location = location;
<button onClick="location = location;">Reload</button>
Probably shortest (12 chars) - use history
history.go()
$(document).on("click", "#refresh_btn", function(event)
{
window.location.replace(window.location.href);
});
It is shortest in JavaScript.
window.location = '';
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.
Related
I have to do some kind of operation on the page refresh or reload. that is when I hit next page or Filter or refresh on the grid. I need to show some confirmation box over this Events.
is there any event which can tell you page is doing filer? refresh or paging? using javascript?
Thanks
If it is refreshing (or the user is leaving the website/closing the browser), window.onunload will fire.
// From MDN
window.onunload = unloadPage;
function unloadPage()
{
alert("unload event detected!");
}
https://developer.mozilla.org/en/DOM/window.onunload
If you just want a confirmation box to allow them to stay, use this:
window.onbeforeunload = function() {
return "Are you sure you want to navigate away?";
}
You can create a hidden field and set its value on first page load. When the page is loaded again, you can check the hidden field. If it's empty then the page is loaded for the first time, else it's refreshed. Some thing like this:
HTML
<body onLoad="CheckPageLoad();">
<input type="hidden" name="visit" id="visit" value="" />
</body>
JS
function CheckPageLoad() {
if (document.getElementById("visit").value == "") {
// This is a fresh page load
document.getElementById("visit").value = "1";
}
else {
// This is a page refresh
}
}
There are some clarification notes on wrestling with this I think are critical.
First, the refresh/hidden field system works on the beginning of the new page copy and after, not on leaving the first page copy.
From my research of this method and a few others, there is no way, primarily due to privacy standards, to detect a refresh of a page during unload or earlier. only after the load of the new page and later.
I had a similar issue request, but basically it was terminate session on exit of page, and while looking through that, found that a browser treats a reload/refresh as two distinct pieces:
close the current window (fires onbeforeunload and onunload js events).
request the page as if you never had it. Session on server of course has no issue, but no querystring changes/added values to the page's last used url.
These happen in just that order as well. Only a custom or non standard browser will behave differently.
$(function () {
if (performance.navigation.type == 1) {
yourFunction();
}
});
More about PerformanceNavigation object returned by performance.navigation
The following will fire an alert when the page is refreshed if the hash tag ends in twoB:
if (window.location.href.match(/\#twoB/))
{
alert('twoB');
}
The issue is that if you've clicked on a few hash tags and then click back in your browser, although the URL includes the hash the alert doesn't fire. How can I make the code fires (ideally only) after a user has gone back or forward with their browser.
I'm using jQuery for this project so i would like a jQuery solution in an ideal world if the syntax is easier.
$(window).on("hashchange", function () {
console.log("hash is now " + window.location.hash);
});
Note that on was added in jQuery 1.7; if you're using an older version, then do $(window).bind instead.
Initially I solved this quite an ugly way of using setInterval to repeatedly check the URL. HTML5s
onpopstate runs when the page is first loaded and then every forward and back navigation aswell.
window.onpopstate = function(){
if (window.location.href.match(/\#twoB/))
{
alert('twoB');
}
}
Why don't you use location.hash instead of href.match? The location.hash should be faster as you are only getting the hash and you don't have to do a match?
I have a scenario to refresh the browser after the page is loaded for first time or one time.
Because the data is not showing properly when the pages is loaded,and when i refresh the browser it is showing.I don't know the reason.
Many Thanks
So you only want the browser to refresh once? Do something like this.
window.onload = function(){
if(!document.location.hash){
window.location = "#loaded";
}
}
or jquery
$(document).ready(function(){
if(document.location.hash){
window.location = "#loaded";
}
});
But in all honesty this is just a temporary solution. As much as you try to cover it up with quick fixes. I guarantee it will come back to haunt you. Well written and structured code will last a lifetime and can always be reused on future projects.
Invariably, you're going to have to use some JavaScript. What you want is for your refresh code to run when the page is completely loaded. You could use the HTML onload event, but there are problems with this (e.g. it will fire before any images are loaded). I would suggest using JQuery's ready() event, if you want to be sure it fires after the entire page is loaded.
Example:
// NOTE: This will only work with JQuery loaded.
$(document).ready(function(){
location.reload(true);
});
Making this only fire on the first page load is a bit more tricky. You could add an anchor suffix to the URL to keep track of whether you've refreshed the page yet or not, and then only refresh if it is not present in the URL:
$(document).ready(function(){
if(location.hash != "#")
{
// Set the URL to whatever it was plus "#".
// (The page will NOT automatically reload.)
location = "#";
// Reload the page.
location.reload(true);
}
});
Alternatively, you could use the query string, since this will automatically refresh the page when changed:
$(document).ready(function(){
var marker = 'r'; // 'r' is for "refreshed"
if(location.search != "?"+marker)
{
// Set the URL to whatever it was plus "?r".
// (This will automatically force a page reload.)
location = "?"+marker;
}
});
Caveat: With either of these samples, if your user bookmarks the page after the "#" or "?r" tag has been added to the URL, the page won't refresh when they revisit the page. If you want it to be bulletproof, you might have to use a cookie instead.
I am curious if there is a way to detect the browser refresh event in javascript specifically. We are using the jQuery.address plugin to provide forward and back button functionality to AJAX functions. The problem I am facing is that this plugin does not seem to detect if the user has refreshed the page.
This code is executed each time the user moves forward or back in the browser history. I would also like it to exexute when the user refreshes.
$.address.init(function(event) {
}).change(function(event) {
SummaryDiv.SwapPanels(newPanelID);
}
Any ideas?
Along these lines, I had a page whose behavior I didn't want to repeat if refreshed, so I changed the hash programmatically as described in this answer.
checkRefresh: function() {
if (document.location.hash === '#visited') {
console.log('Refreshed');
return true;
} else {
document.location.hash = 'visited';
return false;
}
}
UPDATE
I found that at least Mobile Safari would ignore the hash if the refresh occurred automatically (e.g. page data expunged from cache before being viewed again). I ended up using a more complex solution described here.
A naive attempt of mine would be to simply store the current state into some cookie after each change and simply load them again on each page load.
Found this on the web for you...
Has both a javascript clever method along with a cookies method.
http://www.tedpavlic.com/post_detect_refresh_with_javascript.php
On a page refresh, the javascript is also reloaded. So couldn't you specify what you want to happen directly in jQuery's ready method?
I was able to force the change event code to run on refresh by
window.onload = $.address.update(function(){
...
})
In javascript you can do this:
page1.html
<script>
localStorage.removeItem('setear1')
</script>
page2.html
<script>
addEventListener('DOMContentLoaded', () => {
let vengoDeLaPaginaAnterior = localStorage.getItem('setear1')
if (vengoDeLaPaginaAnterior === null) {
localStorage.setItem('setear1', 1)
} else {
document.location.href = 'page1.html'
}
})
</script>
then: if user refresh page, return to previus page.
Say I'm on a page called /example#myanchor1 where myanchor is an anchor in the page.
I'd like to link to /example#myanchor2, but force the page to reload while doing so.
The reason is that I run js to detect the anchor from the url at the page load.
The problem (normally expected behavior) here though, is that the browser just sends me to that specific anchor on the page without reloading the page.
How would I go about doing so? JS is OK.
I would suggest monitoring the anchor in the URL to avoid a reload, that's pretty much the point of using anchors for control-flow. But still here goes. I'd say the easiest way to force a reload using a simple anchor-link would be to use
where in place of $random insert a random number (assuming "dummy" is not interpreted server side). I'm sure there's a way to reload the page after setting the anchor, but it's probably more difficult then simply reacting to the anchor being set and do the stuff you need at that point.
Then again, if you reload the page this way, you can just put myanchor2 as a query parameter instead, and render your stuff server side.
Edit
Note that the link above will reload in all circumstances, if you only need to reload if you're not already on the page, you need to have the dummy variable be more predictable, like so
I would still recommend just monitoring the hash though.
Simple like that
#hardcore
an example
Another way to do that is to set the url, and use window.location.reload() to force the reload.
<a href="/example#myanchor2"
onclick="setTimeout(location.reload.bind(location), 1)">
</a>
Basically, the setTimeout delays the reload. As there is no return false in the onclick, the href is performed. The url is then changed by the href and only after that is the page reloaded.
No need for jQuery, and it is trivial.
My favorite solution, inspired by another answer is:
myanchor2
href link will not be followed so you can use your own preference, for example: "" or "#".
Even though I like the accepted answer I find this more elegant as it doesn't introduce a foreign parameter. And both #Qwerty's and #Stilltorik's answers were causing the hash to disappear after reload for me.
What's the point of using client-side JS if you're going to keep reloading the page all the time anyways? It might be a better idea to monitor the hash for changes even when the page is not reloading.
This page has a hash monitor library and a jQuery plugin to go with it.
If you really want to reload the page, why not use a query string (?foo) instead of a hash?
Another option that hasn't been mentioned yet is to bind event listeners (using jQuery for example) to the links that you care about (might be all of them, might not be) and get the listener to call whatever function you use.
Edit after comment
For example, you might have this code in your HTML:
example1
example2
example3
Then, you could add the following code to bind and respond to the links:
<script type="text/javascript">
$('a.myHash').click(function(e) {
e.preventDefault(); // Prevent the browser from handling the link normally, this stops the page from jumping around. Remove this line if you do want it to jump to the anchor as normal.
var linkHref = $(this).attr('href'); // Grab the URL from the link
if (linkHref.indexOf("#") != -1) { // Check that there's a # character
var hash = linkHref.substr(linkHref.indexOf("#") + 1); // Assign the hash to a variable (it will contain "myanchor1" etc
myFunctionThatDoesStuffWithTheHash(hash); // Call whatever javascript you use when the page loads and pass the hash to it
alert(hash); // Just for fun.
}
});
</script>
Note that I'm using the jQuery class selector to select the links I want to 'monitor', but you can use whatever selector you want.
Depending on how your existing code works, you may need to either modify how/what you pass to it (perhaps you will need to build a full URL including the new hash and pass that across - eg. http://www.example.com/example#myanchor1), or modify the existing code to accept what you pass to it from you new code.
Here's something like what I did (where "anc" isn't used for anything else):
And onload:
window.onload = function() {
var hash = document.location.hash.substring(1);
if (hash.length == 0) {
var anc = getURLParameter("anc");
if (anc != null) {
hash = document.location.hash = anc;
}
}
}
The getURLParameter function is from here
If you need to reload the page using the same anchor and expect the browser to return to that anchor, it won't. It will return to the user's previous scroll position.
Setting a random anchor, overwriting it and then reloading seems to fix it. Not entirely sure why.
var hash = window.location.hash;
window.location.hash = Math.random();
window.location.hash = hash;
window.location.reload();
Try this its help for me
<a onclick="location.href='link.html'">click me</a>
In your anchor tag instead of
click me
As suggested in another answer, monitoring the hash is also an option. I ended up solving it like this so it required minimal code changes. If I had asked the original question, I believe I would have loved to see this option fully explained.
The added benefit is that it allows for additional code for either of the situations (hash changed or page loaded). It also allows you to call the hash change code manually with a custom hash. I used jQuery because it makes the hash change detection a piece of cake.
Here goes!
Move all the code that fires when a hash is detected into a separate independent function:
function openHash(hash) {
// hashy code goes here
return false; // optional: prevents triggering href for onclick calls
}
Then detect your hash for both scenarios like so:
// page load
$(function () {
if(typeof location.hash != typeof undefined) {
// here you can add additional code to trigger only on page load
openHash(location.hash);
}
});
// hash change
$(window).on('hashchange', function() {
// here you can add additional code to trigger only on hash change
openHash(location.hash);
});
And you can also call the code manually now like
Magic
Hope this helps anyone!
Try this by adding simple question mark:
Going to Anchor2 with Refresh