How to Refresh a Page with JavaScript

In this tutorial, we will learn how to refresh a page with JavaScript.

 

The easiest way to reload a page in JavaScript is to use the location object in the browser history API. Due to the nature of JavaScript, there are several different ways to approach using location, though the logical method to use is location.reload().

 

Let's create an HTML button and a JavaScript function that will execute on click. In that function, we will refresh the page.

 

<button id="refresh">Refresh Page</button>
document.getElementById('refresh').onclick = function() {
  location.reload();
}

 

The same thing can be achieved using location.href with location.replace(), though the syntactic sugar of this is associated with a user click action.

 

document.getElementById('refresh').onclick = function() {
  location.replace(location.href);
}

 

A possible advantage of using location.replace() is that data could be appended to the URL before refreshing.

 

Conclusion

You now know how to refresh pages using vanilla JavaScript.

page reload