How to refresh a page using jQuery and javascript

Scenario
It might happen that on a certain event you want to reload or refresh a page. The events over which you may want to trigger page reload are click of a button, click of a link, selection of a checkbox.

To reload or refresh a page, reload() function of javascript location object is used. Syntax is :

location.reload()

Usage
Suppose there is a button on whose click the page needs to be refreshed. Basically, you need to call the above line of code on click of a button. This can be done in two ways :

  1. Using onclick attribute of button. This method is purely based on javascript and does not require jQuery.
  2. Calling a jQuery click event handler for this button.

Following code demonstrates both these approaches.

<html>
   <body>
         <!-- Approach 1 : refresh by onclick handler --> 
         <button onclick="location.reload();">Refresh by onclick attribute
         </button>
         <!-- Approach 2 : refresh by calling an event handler function -->
         <button id="loader">Refresh using event handler</button>

         <script type="text/javascript">
             <!-- bind click event handler to button with id as "loader" -->
             $("#loader").click(function(){
                 location.reload();
             });
         </script>
   </body>
</html>

Both the approaches do the same task but in different ways.

Let’s tweak in :

  1. location is a property of window object. window object represents the current open window.
  2. location object has all information about the current url. You can use it easily obtain parameters such as the url of current page, its host, port, protocol etc.
  3. The reload() function takes an optional true or false parameter. When set to true, it fetches the page from the server rather than the browser cache. The parameter defaults to false, so by default the page may reload from the browser’s cache.
  4. reload() function does not ask a user for confirmation of page refresh. It just refreshes it.
Hope this post helped you on using jquery to refresh a page on an event.

Leave a Reply