Saturday, January 29, 2011

Pre-Loader in Asp.Net with javascript

Preloaders give the viewer something to look at while the Javascript, Css file downloads. Whenever we used javascript files and those file in depended each other or write code on HTML markup of javascript which called the function in those files sometime gives an error or sometime give some ugly shape of loading webpage. In this article I focused to create Pre-loader step by step.
Demo shows in asp.Net, in this demo we create two aspx pages, first page I use as a pre-loader and second page actual page we want to open.click here to download demo
Create a website and then add new aspx page with name of PreLoader.aspx, below code past in markup of it.
        var iLoopCounter = 1;
        var iMaxLoop = 6;
        var iIntervalId;
 
        function BeginPageLoad() {
            // Redirect the browser to another page while keeping focus.
            location.href = "<%=Request.QueryString[“Path”] %>";
            // Update progress meter every 1/2 second.
            iIntervalId = window.setInterval("iLoopCounter=UpdateProgressMeter(iLoopCounter,iMaxLoop);", 500);
        }

BeginPageLoad function called on body load event. Actual page Url pass by Query string. Window.setInterval function start calling UpdateProgressMeter function with initial parameters
<body onload="BeginPageLoad();" >
      function UpdateProgressMeter(iCurrentLoopCounter, iMaximumLoops) {
            var progressMeter = document.getElementById("ProgressMeter")
 
            iCurrentLoopCounter += 1;
            if (iCurrentLoopCounter <= iMaximumLoops) {
                progressMeter.innerHTML += ".";
                return iCurrentLoopCounter;
            }
            else {
                progressMeter.innerHTML = "";
                return 1;
            }
        }        
 
Above function shows the updated the progress of page loads.
            function EndPageLoad() {
            window.clearInterval(iIntervalId);
 
            // Find the object that represents the progress meter.
            var progressMeter = document.getElementById("ProgressMeter")
            progressMeter.innerHTML = "Page Loaded - Now Transferring";
        }

Above method call when page loaded completely. 
<body onload="BeginPageLoad();" onunload="EndPageLoad();">
You can test the pre-loader is working fine or not simple run application like as,
http://localhost/Preloader/PreLoader.aspx?Path=http://www.Choicepk.com



Summary,
We avoid loading page ugly still or old style and don’t want to display the page before loading all javascirpt and Css files. Pre-loader help us to achieve these tasks.
 

No comments:

Post a Comment