You have seen some websites that automatically refresh or reload the webpage after some specific time like 60 seconds. Also, you have noticed some website updates frequently.
Auto refresh functionality is generally used to provide fresh content to a user without the user needing to perform any type of action. Webpages like live scores, result boards, or news feeds change data every time. In this tutorial, we will reload or refresh the webpage using JavaScript or using 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, whenever a user clicks on button it will reload the webpage and display fresh content to a user.
Here, we can also set a time for reloading the webpage automatically with the help of setTimeout() function like the below example.
const myTimeout = setTimeout(reloadPage, 10000);
function reloadPage(){
location.reload(true);
}
Here, we have defined timeout which will call our function every 10 seconds, and in function logic, we have added code for reloading the web page. So whenever a function is called web page reloads.
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.