How to Reload a Page using JavaScript
Read the tutorial and learn information about the method of reloading a page using JavaScript. Also, learn how to make the page be loaded automatically.
The location.reload() Method
JavaScript provides a method popular among developers — <kbd class="highlighted">location.reload()</kbd> — which reloads the page at the current URL.
The location interface represents the URL of the document it is linked to. The location object is a property of the window object, accessed via window.location. One of its methods is <kbd class="highlighted">reload()</kbd>, which is used to reload the document.
JavaScript window.location.reload() method
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<input type="button" value="Reload Page" onclick="window.location.reload()" />
<div>Welcome to W3Docs</div>
</body>
</html>A note from MDN: Firefox supports a non-standard forceGet boolean parameter for location.reload(), to tell Firefox to bypass its cache and force-reload the current document. However, in all other browsers, any parameter you specify in a location.reload() call will be ignored and have no effect of any kind.
A boolean parameter is not part of the current specification for location.reload(). Although many code examples incorrectly use it, it has never been part of any published specification.
The JavaScript <kbd class="highlighted">reload()</kbd> method loads the page from the cache by default.
timeRefresh Function
There is also another way to reload the page using the <kbd class="highlighted">timeRefresh</kbd> function. You can specify how frequently to refresh the page, and it will be loaded non-stop:
How to Reload a Page using JavaScript
function timeRefresh(time) {
setTimeout(() => location.reload(), time);
}Then, you can use it with the onload event, for example, on the <body> element like so:
How to Reload a Page using JavaScript
<body onload="timeRefresh(2000);"> /* refresh every 2 seconds */How to Reload a Page Using the JavaScript History Function
The history.go() method is usually used to navigate back or forward by passing a positive or negative value.
To refresh the page, pass 0:
How to Reload a Page using JavaScript
history.go(0);