JavaScript Refresh Page

In JavaScript, you refresh the page using document.location.reload(). You can add the true keyword to force the reloaded page to come from the server (instead of cache). Alternatively, you can use the false keyword to reload the page from the cache.

This code can be called automatically upon an event or simply when the user clicks on a link.

Example JavaScript Refresh Code

CodeResult

Auto-Refresh

You can also use JavaScript to refresh the page automatically after a given time period. Here, we are refreshing the page 5 seconds after the page loads. This results in the page continuously refreshing every 5 seconds.

This code...

Copy to Clipboard
<html>
<head>
<script type="text/JavaScript">
<!--
function timedRefresh(timeoutPeriod) {
	setTimeout("location.reload(true);",timeoutPeriod);
}
//   -->
</script>
</head>
<body onload="JavaScript:timedRefresh(5000);">
<p>This page will refresh every 5 seconds. This is because we're using the 'onload' event to call our function. We are passing in the value '5000', which equals 5 seconds.</p>
<p>But hey, try not to annoy your users too much with unnecessary page refreshes every few seconds!</p>
</body>
</html>

View the result (opens in new window)

You can achieve the same effect using the HTML meta tag.

Other Refresh Tricks

By including your refresh code in a function, you can have complete control over when the page is refreshed.

Example 1

Instead of having the "page refresh" function called automatically when the page loads, you can call it only when the user performs some action - such as clicking on a link.

Example:

CodeResult

Refresh this page in 2 seconds
Refresh this page in 5 seconds

Example 2

You can use conditional statements to determine whether or not to refresh the page. Here's a basic example of using a "confirm" box to ask the user if it's OK to refresh the page.

CodeResult

Refresh Page

By incorporating refresh code with a JavaScript function, you can trigger a refresh at any time that makes sense to your web application.

HTML Refresh

The above examples will only work as long as the user has JavaScript enabled on their browser. You can also use HTML to refresh a page automatically once the page has loaded. This is achieved by using the HTML meta tag.

Enjoy this page?

Sponsored Link: Design CODE-FREE Websites

Check a Domain:

ZappyHost Logo
Webydo Banner Ad