Refresh/Reload a page with JavaScript/jQuery
This post will discuss how to reload/refresh a webpage with JavaScript.
There are 535 ways to reload the page using JavaScript, all of which use the Location object. This post provides an overview of the important methods to accomplish this.
1. Using location.reload() function
The standard approach to reload the current URL with JavaScript uses the location.reload() method. It takes an optional boolean parameter. The true parameter will force the latest copy from the server, whereas the empty or false parameter will serve the cached copy if present.
|
1 2 3 4 5 |
window.addEventListener("load", event => { document.getElementById("reload").onclick = function() { location.reload(true); } }); |
2. Using location.href
When you assign a URL to the window.location.href property, the associated document navigates to the new page. We can use it in the following manner for reloading a page:
|
1 |
window.location.href = window.location.href; |
Since window is a global object, it can be shortened to:
|
1 |
location.href = location.href; |
Note that the location is a synonym of location.href. So, you can skip the href attribute as well.
|
1 |
location = location; |
3. Using location.assign() function
You can also reload a page using the location.assign() or location.replace() method.
|
1 2 3 4 5 |
window.addEventListener("load", event => { document.getElementById("reload").onclick = function() { location.assign(location.href); // or, use `location.assign(location)` } }); |
or
|
1 2 3 4 5 |
window.addEventListener("load", event => { document.getElementById("reload").onclick = function() { location.replace(location.href); // or, use `location.replace(location)` } }); |
4. Using jQuery
With jQuery, you can assign the current URL to the href property of the location object using the .prop() or .attr() method.
|
1 2 3 4 5 |
$(document).ready(function() { $("#submit").click(function() { $(location).prop("href", location.href); }) }); |
You can also directly assign a value to the location object.
|
1 2 3 |
$(document).ready(function() { $(window).prop("location", location.href); }); |
That’s all about reloading a page in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)