Refresh or Reload a Page using JQuery.

March 05th, 2013
Many a times we need to Refresh or Reload an active web page or the web pages we embed inside the parent page. The active page or the embedded pages can be refreshed or reloaded either manually or automatically using JQuery.

Here in this article, we will see how to refresh a page manually using a Button control and automatically by setting a time for the page to reload.

To achieve this we will use JavaScript’s location.reload() method inside the JQuery $(document).ready() function. Both, manual and automatic activation events will be written inside the .ready() function.

Method “location.reload()” also accepts a Boolean parameter “forceGet”, which can be either “true” or “false”. Setting “location.reload(true);” ensures that the current page is fully loaded ignoring the “cache”.

The JQuery $(document).ready(function() {}) ensures that the entire page is fully loaded before any event is handled.

The Markup and Script
<html>
<head>
    <title>Refresh or Reload a Page Using JQuery</title>

    <script> type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
            </script>
</head>

<body>
    <div><input id="btReload" type="button" value="Reload Page" /></div>
</body>

<script> type="text/javascript">

    $(document).ready(function() {
        $('#btReload').click(function() { location.reload(true); });    // RELOAD PAGE ON BUTTON CLICK EVENT.

        // SET AUTOMATIC PAGE RELOAD TIME TO 5000 MILISECONDS (5 SECONDS).
        setInterval('refreshPage()', 5000);
    });

    function refreshPage() { location.reload(); }

</script>
</html>

The automatic “Reloading” of the page will be triggered using the “setInterval()” method. This method takes 2 parameters. First parameter is a “Code” or a “Function” which will be executed and second, the intervals the function will be executed repeatedly. In the above demo, we have set the time as “5000” milliseconds or “5” seconds to be precise.

comments powered by Disqus

Join our Google Plus Community and be a part of a discussion!