Henry's Web Notes

My dev notes about the web

Archive for the ‘JavaScript’ Category

JavaScript: How To Force Page To Reload

Sunday, June 24th, 2007

When you want to load a page on a browser, you would normally click the Refresh / Reload button or press F5 or CTRL-R on your keyboard. If you set your browser to cache previously viewed pages, doing a normal page reload will cause the browser to fetch the requested page from cache unless otherwise instructed by a script or meta tag in the page. When this happens, images and css will be read from cache and form fields will also retain their values (this included text, textarea, radio button and checkbox).

In order to completely force a page to reload, which means, instructing the browser to skip the cached data and re-fetch everything from the server, you need to press CTRL-F5 on IE and Firefox or Command-R on Mac-Safari.

In JavaScript, there are also different ways to reload a page. Here are the methods for a normal page reload:

window.location.assign(url);
Loads the page at the the provided URL.

window.location.replace(url);
Same as assign() method except that when replace() is used, the current page will not be saved in the session history as it was replaced by the provided URL.

document.location = url;
Technically, location is a read-only property of the document. But some browsers allow you to assign a URL to it, which causes the page to reload. The reason for this is because whenever the location property is modified, a page will reload with the new assigned URL. I recommend using window.location for browser compatibility.

window.location.href = url;
Same as document.location

The other properties of location that when modified will reload the page are hash, host, hostname, pathname, port, protocol and search.

What if you want to completely force a page to reload? Say, you want to clear all entered values in a form or maybe you have modified your CSS and you want to make sure that the page will pickup the new changes. In order to do so, you can do the following:

window.location.reload(true);

The reload method accepts a boolean value, which, when it is true, causes the page to always fetch document from the server. When none is specified, it defaults to false, which may reload the page from its cache.

As you can see, the methods for forcing a page to reload has their own purposes. If you simply want to reload the page and do not care about displaying fresh data, you should not always force it to reload from the server to avoid making http requests, which is an expensive call and a waste of bandwidth. You are not only calling the page itself but you maybe reloading an external CSS page too.