In JavaScript, we can refresh a page using the following methods:
location.reload()
history.go(0)
location.reload()
methodThis method reloads the current URL, like the browser's refresh button.
This method does not accept any parameter.
This method does not return any value.
Let's see an example of the location.reload()
method in the code snippet below:
const btn = document.getElementById('btn') // attach event listener on btn btn.addEventListener('click', () => { // reload the page window.location.reload() })
In the index.html
file,
Line 6: We create a button with id="btn"
.
In the index.js
file,
Line 1: We use the getElementById()
method to find the element with id="btn"
.
Line 4: We attach the click
event listener to the button.
Line 6: We refresh the page using location.reload()
when the button is clicked.
history.go(0)
methodThis method uses the History object of the browser to reload a URL, depending on the value of the specified parameter.
number
: This specifies the position to which we want to move with respect to the current URL. A negative
value will move backward in history, whereas a positive
value will move forward. If no parameter is passed or if the value is 0
, this method will reload the current URL.
This method does not return any value.
Let's see an example of the history.go()
method in the code snippet below:
const btn = document.getElementById('btn') // attach event listener on btn btn.addEventListener('click', () => { // reload the page history.go(0); })
In the index.html
file,
Line 6: We create a button with id="btn"
.
In the index.js
file,
Line 1: We use the getElementById()
method to find the element with id="btn"
.
Line 4: We attach the click
event listener to the button.
Line 6: We refresh the page using history.go()
when the button is clicked.
Besides these methods, we can also refresh the page by reassigning a value to the current URL, as shown below: