Sunday, July 16, 2017

JavaScript provides several ways to reload or refresh an HTML page but the standard way to do this job is by using window.location object. This object provides a reload() method which instructs the browser to reload the page. The browser can do it from its cache or from the server, which depends upon optional parameter i.e. reload(true) will reload the page from the server but reload(false) will only reload the page from browser's cache, which may or may not represent the current version at the server.

You can combine both jQuery and JavaScript to wrap the page refresh code as shown in our example. Btw, this is not the only way to refresh a page in JavaScript, you can also use history.go(0) and location.replcace(locatoin.pathname) to reload the page.

JavaScript and jQuery example to reload a page

In this example, I will tell you how to reload a page from both server and browser's cache using jQuery and JavaScript. In our HTML we have two buttons, one for reloading page from the server and other from refresh page from browser's cache. Though location.reload() will work in all browser, you can also use jQuery to wrap other code e.g. attaching a click handler to the two buttons.

That's all about how to reload or refresh a page in jQuery using JavaScript. Just remember that window.location.reload() will instruct the browser to reload the page, which means downloading data from the server, parsing, and displaying it. You can also reload a page from browser's cache by using the location.reload(false) method. You can read more about jQuery methods on jQuery in Action book, one of the best resources to learn and use jQuery in real world projects.