How to refresh a page using JavaScript

Overview

In JavaScript, we can refresh a page using the following methods:

  • location.reload()

  • history.go(0)

The location.reload() method

This method reloads the current URL, like the browser's refresh button.

Syntax

Error: Code Block Widget Crashed, Please Contact Support

Parameters

This method does not accept any parameter.

Return values

This method does not return any value.

Example

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()
})
The implementation of location.reload()

Explanation

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.

2. The history.go(0) method

This method uses the History object of the browser to reload a URL, depending on the value of the specified parameter.

Syntax

Error: Code Block Widget Crashed, Please Contact Support

Parameters

  • 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.

Return values

This method does not return any value.

Example

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);
})
The implementation of history.go()

Explanation

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:

Error: Code Block Widget Crashed, Please Contact Support

Free Resources