This is a short guide on how to reload / refresh a page using JavaScript. This can be particularly useful piece of code to use after an AJAX form has been submitted.
There are actually over 500 ways to reload a page using JavaScript. However, I will be focusing on the most popular approaches.
The location.reload method.
If you’re using JavaScript 1.2 or above, you can use the location.reload method like so:
//Refresh the current page. window.location.reload(false);
The location.reload method is supported by all major browsers, including Internet Explorer.
If you’re wondering why I am passing a boolean FALSE value in as a parameter, it is because this method allows you to specify whether the refresh should be a hard refresh or not.
Forcing a hard refresh.
If you want to force a hard refresh and tell the browser to reload the page without using the cache, you can set the forcedReload parameter to true:
//Reload the page and ignore the browser cache. window.location.reload(true);
The JavaScript above will reload the page from the server and ignore the browser’s cache.
The location.href property.
As an alternate to location.reload, you can set the location.href property. By modifying the location.href property, you can tell the browser to redirect to a certain URL. This means that we can reload the current page by redirecting to the current URL:
//Construct the current URL. var currentURL = window.location.pathname + window.location.search + window.location.hash; //Redirect to the current URL. window.location.href = currentURL;
The location.href property has been available since JavaScript version 1.0.
It is worth noting that the above piece of code will create an entry in the user’s browser history.
The location.replace method.
If you do not want the reload to appear in the user’s browser history, you can use the location.replace method. This method has been available since JavaScript version 1.1.
//Construct the current URL. var currentURL = window.location.pathname + window.location.search + window.location.hash; //"Replace" the current URL with the current URL. window.location.replace(currentURL);
This method is also supported by all major browsers.
That’s pretty much it! Personally, I would suggest that you use the location.reload method seen in the first example unless you have identified a specific reason to avoid it!
Good luck!