HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

How can I use JavaScript to reload the page?

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascripthowusereloadcanthepage

Problem

Most often than not, window.location.reload() is all you need to reload the current page. This method behaves exactly like the browser's reload button, using the same cache rules and everything.
While window.location.reload() is the most common way to reload a page, there are some nuances that you might need to be aware of.
As stated already, compatibility shouldn't be an issue, so we're not going to delve into that. However, there's a notable oddity concerning the method's arguments. As it turns out, Firefox used to support an optional forceGet boolean argument, which you might come across in older code. This means that passing a value of true to the method would bypass the browser's cache.
Apart from that, window.location.reload() will reload the page keeping POST data in forms, which might not be desired. In those situations, you might want to assign window.location.href to itself to cause a reload. This will cause the page to reload, but will also clear the POST data.
This technique also comes with some caveats. For example, if the current URL contains a hash, the page won't reload. In this case, you might want to use String.prototype.split() to remove the hash from the URL and then assign it to itself.

Solution

// Reload the page
window.location.reload();


As stated already, compatibility shouldn't be an issue, so we're not going to delve into that. However, there's a notable oddity concerning the method's arguments. As it turns out, Firefox used to support an optional forceGet boolean argument, which you might come across in older code. This means that passing a value of true to the method would bypass the browser's cache.
Apart from that, window.location.reload() will reload the page keeping POST data in forms, which might not be desired. In those situations, you might want to assign window.location.href to itself to cause a reload. This will cause the page to reload, but will also clear the POST data.
This technique also comes with some caveats. For example, if the current URL contains a hash, the page won't reload. In this case, you might want to use String.prototype.split() to remove the hash from the URL and then assign it to itself.
As you can see, each technique has its pros and cons, so you should choose the one that best suits your needs. That being said, window.location.reload() is the most common and reliable way to reload a page, so it's the one you should use most of the time.

Code Snippets

// Reload the page
window.location.reload();
// Bypass cache in Firefox
window.location.reload(true);
// Clear POST data
window.location.href = window.location.href;

Context

From 30-seconds-of-code: reload-page

Revisions (0)

No revisions yet.