Contents
If you need to reload a page in JavaScript, there are a few ways to do it. Here’s how to reload a page using the standard method, as well as using the reload method from the jQuery library.
Checkout this video:
Introduction
In JavaScript, the function to reload a page is called “location.reload()”. The advantage of using this method instead of simply refreshing the page is that you can choose to refresh only certain parts of the page (such as the content), while other parts (such as the navigation) remain unchanged.
To use location.reload(), simply call it within your code:
location.reload();
You can also pass a true or false parameter to location.reload() to force a cache refresh or not:
location.reload(true); // Forces a cache refresh
location.reload(false); // Does not force a cache refresh
The location.reload() Method
The location.reload() method is used to reload the current document.
The reload() method does the same as the reload button in your browser. It can also be used to refresh a page, after an Ajax request.
Note: There are several ways to reload a page using JavaScript. The example above uses the location.reload() method to refresh the page.
The history.go(0) Method
The history.go(0) method will reload the current page from the server. This is equivalent to clicking the refresh button in the browser.
The advantage of this method over the window.location.reload() method is that it does not re-send POST data.
This method is executed automatically when a user clicks on the browser’s refresh button.
The location.href Method
The location.href property reloads the current page.
The following code shows how to use the location.href method:
location.href = “http://www.example.com”;
This code will cause the current page to be reloaded from the server.
The location.replace() Method
You can use the location.replace() method to reload a page. This method replaces the current page in the browser’s history stack, so if you use it to reload a page, you won’t be able to use the back button to go back to the previous page.
Here’s an example of how to use the location.replace() method:
location.replace(“http://www.example.com”);
If you want to be able to go back to the previous page, you can use the history.back() method instead:
history.back();
Conclusion
In this article, we showed you how to reload a page in JavaScript. We also showed you how to use the Location object to get information about the current page.