Sometimes, developers want to refresh the web page frequently while creating web applications, such as blogs or websites where the contents may vary depending on user actions. Any updated information based on these user interactions will be displayed when the page is refreshed or reloaded. For this purpose, JavaScript offers some prebuilt methods that will be discussed below.
This post will illustrate the ways to reload a page using JavaScript.
How to Reload a Page Using JavaScript?
For reloading or refreshing a page, use the following methods in JavaScript:
Method 1: Reload a Page Using reload() Method
Use the “location.reload()” method to reload the page. It acts just like a browser’s refresh button. The “reload()” method is responsible for page reloading, while the “location” is an interface that indicates the actual location (URL) of the object to which it is associated. The URL of the page to refresh is accessible by either “document.location” or “window.location”.
Syntax
Use the following syntax for reloading the current page using reload() method:
Example 1: Refresh on a Button Click
Create a button and attach an “onclick” event on it that will call the JavaScript predefined “reload()” method:
The output indicates that the page is refreshed or reloaded on a button click:
Example 2: Auto Refresh Using setTimeout() Method With reload() Method
Set the time for automatically refreshing the page using the “setTimeout()” method. First, we will define a method “refresh()” that takes a time interval as a parameter to refresh the page after that time. Call the setTimeout() method and then call the reload() method:
setTimeout(() => {
document.location.reload(true);
}, time);
}
Here, we will set the time 2 seconds to refresh the page after every two seconds:
As you can see that the page is automatically refreshed after 2 seconds:
Method 2: Reload a Page Using go() Method
Another approach for refreshing a page is the “history.go()” method. Giving in either a positive or negative value can be used as usual to move backward or forward. For a refresh, pass the “0” neutral value or nothing.
Syntax
Follow the given syntax for reloading the page:
Example
Here, we will call the “history.go()” method in the click event of the button:
Output
That’s all about reloading/refreshing web pages using JavaScript.
Conclusion
For reloading a web page using JavaScript, use the “window.location.reload()” method or the “history.go()” method. The reload() method is the most commonly used approach for reloading or refreshing web pages. This post illustrated the ways to refresh a page using JavaScript.