Register Login

How to Refresh a Web Page in JavaScript?

24 Jul 2020 1:02 pm || 0

While using JavaScript, you may want to refresh a web page with your code. Let us look at the different ways to do so.

We will here learn the following methods to refresh a web page in JavaScript:

1. Refreshing a Page in JavaScript

In JavaScript, page is reloaded using the document.location.reload() method or the window.location.reload() method. The location.reload() method gives the same result as pressing the reload button on your browser.

This method reloads the page from directly the browser’s cache by default. If the forceGet property is set to true, the web page will be reloaded from the server.  

Reload Page from Cache

Example

<script>
location.reload();
</script>

Reload Page from Server (without Cache)

<script>
location.reload(true);
</script>

The default parameter is False here. So, if the parameter is left blank, object.reload() reloads the page using the broswer’s cached data, i.e. is identical to using the method as object.reload(false).

2. Auto Refresh Page After 5 Second

<script>
setTimeout("location.reload(true);", 1000);
</script>

You can also use JavaScript to refresh the web page automatically after a specified interval. Using the setTimeout() method here, we are refreshing the page automatically 5 seconds after it reloads.

3. Refresh Page on Button Click

<body>
<input type="button" value="Reload Page" onClick="window.location.reload(true)">
</body>

Instead of automatically refreshing a web page using a method, you can call the method when a user performs an event, such as a button click. In this example, you can see that page will get refreshed using the location.reload() method after the user clicks on the Reload Page button.

4. Using History Function

Example

<body>
<input type="button" value="Reload Page" onClick="history.go(0)">
</body>

The JavaScript, the window object has a history property which is used for page refreshing. The history.go() method in this example helps in manipulating the browser session history.

Here 0 is the history parameter,

  • 0 = current Page
  • -1 = Previous page

This parameter lets you navigate back and forth within your web page session history.

5. Refresh Page in HTML

<meta http-equiv="refresh" content="1">

The code will refresh the HTML document after every 1 second. The http-equiv is set to refresh and the content attribute is set to the interval of 1 second. 

6. Using Jquery

<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$( document ).ready(function() {
    $("body").load(window.location.href);
});
</script>

The window.location has a href property. This returns the URL of the current website. In this example, this property is used for reloading and refreshing the current page. This property can also be used to target another page and refresh it.