Reload webpage using JavaScript

Sometimes you may need to reload a webpage using JavaScript to keep the content up to date without requiring any user action. This feature is commonly seen on websites that auto-refresh after a set interval, such as live scoreboards, news feeds, or result boards.

Auto refresh functionality helps deliver fresh content seamlessly, enhancing the user experience. In this tutorial, we will explore simple ways to reload or refresh a webpage using JavaScript as well as meta tags.

Reload or Refresh Page Using JavaScript

Here, we will see how to reload a webpage using JavaScript. JavaScript has location() method which has much functionality related to webpage actions like reloading pages, changing locations, and more.

The location object has information related to current variables like the previous page, current URL, hostname, and more. Here, we will use location.reload() method to refresh the webpage with or without user interaction.

Below is a syntax for reloading webpage using the location() function:

window.location.reload();
//OR
window.location.reload(true);

Here, the reload method reloads the page but it has an optional parameter by boolean type. If you don’t pass the value then it will reload webpage from the cache otherwise it will get fresh content from a server.

Let’s take example of manually reload page using button click first:

$("#btn").click(function() {
   location.reload(true);
});

In the above example, when a user clicks the button, the webpage reloads and shows fresh content. You can also set a time to reload the page automatically using the setTimeout() function, as shown below.

const myTimeout = setTimeout(reloadPage, 10000);

function reloadPage(){
   location.reload(true);
}

We defined a timeout that calls our function every 10 seconds. Inside the function, we added code to reload the webpage. Each time the function runs, the page refreshes automatically.

Reload page with Meta tag

This method doesn’t require JavaScript code to add. But with meta tags, we can easily reload web pages using HTML tags at specific times. Let’s assume you have to reload the webpage every minute then you can also use HTML meta tag for it.

We have a meta tag inside the head tag of the HTML code, as in the case of every other meta tag. To set the time interval in seconds, we use the content attribute.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Reload Web page using JavaScript</title>
        <meta http-equiv="refresh" content="60">
    </head>
    <body>
        <h4>Reload Web page using JavaScript</h4>
    </body>
</html>

Conclusion

In this article, we have reloaded web pages using JavaScript and HTML tags. Both methods can be used to reload web pages automatically so you can use it as per your requirements.

You might also find it helpful to explore how to get file extension in JavaScript for handling uploaded files more effectively.