Page Refresh in JavaScript

Refreshing a page from JavaScript is not used much but still it comes handy sometimes (like when you want to override all changes that your user has done in the page). I used to use it a few years ago when I didn’t knew anything about AJAX but now AJAX does everything. Still I thought about writing this down. Maybe it might help you (or even me in the decades to come, if ever I forget).

It is just a single line that does the job. Just type:
location.href=location.href;

You assign the window’s location to itself which forces the browser to reload the page since it observes any changes made to the URL. In a function you might implement it like:

function doSomething() {
  // do something here which would eventually
  // require a full-page refresh
  location.href=location.href;
}

Done. But note one thing, everything you write after that refreshing line won’t be executed since the control will pass to the browser to reload the page. In other words, it is like a return statement of a function.

Advertisements

Your Thoughts -

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s