javascript logo

Refreshing or reloading a web page in JavaScript isn’t all that difficult. There is the straightforward window.location.reload (or just location.reload) method, and then there are a few less intuitive approaches that achieve the same effect. In the this lesson, I’ll show two examples of how to reload a web page using JavaScript. Get ready to get reloaded!

Explore JavaScript Courses

First, the aforementioned location.reload method: This method is inherent to the location property of the global/window object. Using it might look something like this:

Live code example: https://jsfiddle.net/c5gntsfh/

The method is pretty self-explanatory, however it does take an optional argument whose functionality and purpose may not be immediately apparent. The optional argument taken by the reload method is meant to be a boolean value of either true or false. If there is no argument passed (like in the examples above), then the method behaves the same as if the value of false was passed to it. In both cases, the browser will try to reload the page from its cached source. Conversely, if a value of true is passed to the reload method (e.g., location.reload(true);), then the browser will reload the page from the original server location.

Okay great! We’ve got the reload method now, but the location.reload method isn’t the only means for achieving a page reload in JavaScript. What’s more, sometimes you may find yourself needing to get around blocking of the reload method that some pages will do. For example, on CodePen (http://www.codepen.io), for whatever reason, the developers behind application decided to remove the location.reload method. So… what can we do instead?

Explore JavaScript Courses

Instead of using the location.reload method, we can simply set the location.href property to its current value. Doing so essentially causes the browser to reload. For example:

Live code example: http://codepen.io/anon/pen/PNgLOw?editors=0010

*Do note that neither of the above approaches refresh the console like actually clicking the reload button in your browser will; just something to be aware of…

More on the global/window object’s location and associated properties (location.href is the first property listed): https://developer.mozilla.org/en-US/docs/Web/API/Location

So there you have it! Two ways to reload a page in JavaScript; one relatively  straightforward, and one perhaps a bit more obscure. Both have their place and the reasons for using each should be considered when writing your scripts.

Now get out there and reload some pages! 🙂

Comments