How can I refresh a page with jQuery?
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();