How To Reload Page In Javascript

There are instances when you might want to refresh or reload a web page using JavaScript. For example, you may want to refresh the page after a certain event occurs, like when the user submits a form or clicks a button. In this blog post, we will explore different ways to reload a web page using JavaScript.

Method 1: Using the window.location.reload() Method

The most common method to refresh a web page using JavaScript is by calling the window.location.reload() method. This method can be called without any arguments, and it will refresh the current page:

window.location.reload();

The window.location.reload() method also accepts an optional argument: a boolean value that, when set to true, forces the browser to perform a hard reload, bypassing the cache. By default, this value is set to false, meaning the browser will perform a soft reload using the cached resources:

window.location.reload(true); // Hard reload
window.location.reload(false); // Soft reload (default)

Method 2: Setting the window.location.href Property

Another way to refresh the page using JavaScript is by setting the window.location.href property to its current value. This action tells the browser to navigate to the same URL, which effectively refreshes the page:

window.location.href = window.location.href;

Method 3: Using the location.replace() Method

Finally, you can use the location.replace() method to refresh a page. This method replaces the current document with the specified URL, and in our case, we’ll replace it with the same URL:

location.replace(window.location.href);

It is important to note that using location.replace() will not add a new entry to the browser’s history. This means that if the user clicks the back button after the page has been refreshed, they will be taken to the page they visited before the current one, rather than the refreshed version of the current page.

Conclusion

In this blog post, we have explored three different methods to refresh a web page using JavaScript: the window.location.reload() method, setting the window.location.href property, and using the location.replace() method. Choose the method that best fits your use case, and happy coding!