Click here to Skip to main content
Click here to Skip to main content

ASP.NET/ AJAX Page Loader Progress Bar/ Splash Screen

By , 1 Oct 2006
 

Introduction

Today, complex server controls and extensive JavaScript libraries (e.g., AJAX ) are very common. They can considerably increase the size and the loading time of your page. Unfortunately, it is very hard to catch how slow your page is while you are in the development environment. You will be surprised to see how long some users have to wait until your page is completely downloaded. Wouldn't it be nice if you could communicate to the users to stay patient until the page and scripts are downloaded? In some cases, you would rather hide your page until it is fully downloaded to avoid premature events when your scripts are still loading. This article shows how you can display the loading process of your page with a progress bar. Additionally, you can use this as a splash window to show messages, news, or ads that you want the user to see first.

The technique discussed here is not limited to ASP.NET. If you are using other server-side scripting languages, keep on reading!

Update: Live sample.

Using the code

To make life easier, I encapsulated all the code into the LoadingNotifier class. To use the LoadingNotifier, your page inherits the LoadingNotifier class. First, you initialize the loading progress bar by calling initLoader() in a server script tag, e.g.: <%initLoader(strMsg);%>. This method writes JavaScript to the response object and calls the Flush() method to send the buffered output to the client. This JavaScript function adds the progress bar to the DOM and shows the page is being loaded. From here, on each achieved milestone, you call the Notify(strProgressPercent, strLoadingStatusMsg) method of LoadingNotifier and pass in the progress percentage and the status message. Each call to the Notify method writes a JavaScript function to the Response that updates the progress bar. When the progress bar reaches 100%, it automatically gets removed from the DOM. The progress bar is totally customizable, and takes its stylesheet from the page theme. You can set a background color for the progress bar container to hide the page until it is 100% loaded.

<%@ Page Language="C#" Inherits="LoadingNotifier" Theme="Default" %>
<%%
    //shahin@themorningoutline.com provided this UNDER GNU GPL 
    // For more inforamtion visit http://www.themorningoutline.com/
   
    // Page Inhertits the LoadNotifier Class 
 %>

<!DOCTYPE html >
<html>
<head runat="server">
    <title>www.themorningoutline.com ASP.NET Sample</title>
</head>
<body style="background-color: #999999; font-size: 12px; 
             font-family: Verdana, Arial, Helvetica, sans-serif;">
  
  
    <% //Initilize thr Progress Bar and show a message
        initNotify("Welcome to theMorningOutline. Free tickets from today!");
        System.Threading.Thread.Sleep(3000);
    %>
    <form id="form1" runat="server">
  
        <span style="font-size: 12pt"><strong>
          <span style="color: #ffffff">Select Your Departure Date: </span></strong> 
          </span>
          
        <asp:Calendar ID="Calendar1" runat="server"></asp:Calendar>
        <br />
        <% 
            // We have achieved a milestone. Let the user know!
            Notify("30", "Loading Departure Calendar Completed ...");
            // Simulate Internet dalay
           System.Threading.Thread.Sleep(2000);
           
             %>
        <span style="font-size: 12pt"><span style="color: #ffffff">
           <strong>Select Your Return Date: </strong>
           <span style="color: #000000"> </span></span></span>
        <asp:Calendar ID="Calendar2" runat="server"></asp:Calendar>
        <br />
      
           <% 
           Notify("60", "Loading Arrival Calendar Completed ...");
           System.Threading.Thread.Sleep(2000);
           
             %>
               <span style="font-size: 14pt">
               <span style="color: #ffffff">Your Recent Flights:</span><strong>
               <spanstyle="color: #ffffff"> </span></strong></span>  <br />
        
        <span style="font-size: 12pt"><span style="color: #ffffff"></span>
        </span>
        <asp:GridView ID="GridView1" runat="server" 
            AutoGenerateColumns="False" CellPadding="4"
            DataSourceID="XmlDataSource" ForeColor="#333333" 
            GridLines="None" Style="border-left-color: gray;
            border-bottom-color: gray; border-top-style: outset; border-top-color: gray;
            border-right-style: outset; border-left-style: outset; border-right-color: gray;
            border-bottom-style: outset">
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <Columns>
                <asp:BoundField DataField="id" HeaderText="id" SortExpression="id" />
                <asp:BoundField DataField="Origin" 
                      HeaderText="Origin" SortExpression="Origin" />
                <asp:BoundField DataField="Destination" 
                    HeaderText="Destination" SortExpression="Destination" />
                <asp:BoundField DataField="Duration" 
                       HeaderText="Duration" SortExpression="Duration" />
                <asp:BoundField DataField="Price" 
                       HeaderText="Price" SortExpression="Price" />
            </Columns>
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
            <EditRowStyle BackColor="#999999" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
        </asp:GridView>
        <asp:XmlDataSource ID="XmlDataSource" runat="server" 
                  DataFile="~/Source.xml" XPath="/travel/Itinerary">
        </asp:XmlDataSource>
        <%
            Notify("100", "Loading Your Previous Trips Completed...");
          System.Threading.Thread.Sleep(2000);
         %>
    </form>
     
    
</body>
</html>

The code-behind:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

// shahin@themorningoutline.com provided this UNDER GNU GPL 
//For more inforamtion visit www.themorningoutline.com
public class LoadingNotifier: System.Web.UI.Page
{
 
    public  void initNotify( string StrSplash)
    {
        // Only do this on the first call to the page
        if ((!IsCallback) && (!IsPostBack))
        {
            //Register loadingNotifier.js for showing the Progress Bar
            Response.Write(string.Format(@"<script type='text/javascript' 
                   src='scripts/loadingNotifier.js'></script>
              <script language="'javascript'" type='text/javascript'>
              initLoader('{0}');
              </script>",StrSplash));
           // Send it to the client
            Response.Flush();
            
        }

    }
    public  void Notify(string strPercent, string strMessage)
    {
        // Only do this on the first call to the page
        if ((!IsCallback) && (!IsPostBack))
        {
            //Update the Progress bar

            Response.Write(string.Format("<script language="'javascript'" type" + 
                           "='text/javascript'>setProgress({0},'{1}'); </script>", 
                           strPercent, strMessage));
            Response.Flush();
        }
    }
}

Remember that the Page_Load event has been processed before the page is being downloaded, therefore if you have expensive operations in your Page_Load event, you cannot display the processing progress using this method. This method uses the W3C Standard DOM methods which require the body tag to be present to display the progress bar. To display the loading status during Page_Load or other events which are processed prior to sending the page to the client, you can directly write your status message to the Response object and call the Flush method. When the page is completed at the client, you should clean up your status messages.

Conclusion

Finally remember that using the LoadingNotifier class actually slows down the loading process of your page, and it should be avoided unless your page is really heavy. Comments here!

Cheers!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Shahin__
Web Developer
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 1memberlalupatel25 Nov '10 - 20:53 
OK
GeneralHii :)memberNavin C. Pandit16 Dec '09 - 22:55 
Hii Dear,
Really cool n nice task you did. Many thanks for sharing.
 
Thumbs Up | :thumbsup:
 
Regards,
Navin C.
(Software Engineer)
Mail: navin2k6@gmail.com

GeneralLoading Gridview Progressmemberkjward16 Oct '07 - 4:21 
thanks for the code sample. i'd like to use it on my webform which starts by grabbing a bunch of data from a database, and populates a gridview control. while it's out there doing its thing, i'd like to keep the user entertained so they don't get bored. this is all done in c# code behind, which the aspx already inherits, so i can't inherit the LoadingNotifier, too, can i?
 
so how do i implement your cool notify code to keep the user informed?
 
thanks in advance
 
kjward

QuestionHelp &quot;Response is not available in this context. &quot; [modified]memberrafiki31@gmail.com15 Aug '07 - 7:14 
Im getting this type of error i dont understand why. I placed everything in the aspx no in code behind. All do i am conecting to a data base and retrieving information. and i have placed the initNotify right after de body. and i get the following error,
 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
 

Exception Details: System.Web.HttpException: Response is not available in this context.
 
I also tried to place de sub's call in the codebehind right before i conectect to the de BD (thats where i placed de initNotify()) and after i get the sqldatareader i placed another notify()
but it still throws the same error .. what am i doing wrong pls help :S
 
The page works like this .. i use a textbox in page1.aspx so that the user put in what he would like to look for .. i do a postbackurl to page2.aspx. In page2.aspx in my page_load i have that if its not a postback then conecto to the database and get the information which i store in a sqldatareader, and this fills my textboxes from page2.aspx....
 
hope i was clear enough Sniff | :^) Frown | :( img src="/script/Forums/Images/smiley_confused.gif" align="top" alt="Confused | :confused:" />
 

 
-- modified at 13:19 Wednesday 15th August, 2007
GeneralRe: Help &quot;Response is not available in this context. &quot;membermohit rawat19 Feb '08 - 0:28 
Use the class functions in code file then try to use
Generalcode behindmemberdsmportal7 Apr '07 - 12:52 
how do i use in code behind?
example, when the user click on the button or when te page is loadinf first time (code behind)?
 
thanks
GeneralRe: code behindmemberdsmportal8 Apr '07 - 4:56 
its me again... i just wanted to be more clear so that i may get the right and correct response:
 
I have found your article and love the idea/concept. The question I have is: does it work in the code behind pages or just inline code? I tried using code.
 
I have a lot of logic in my pages and don’t want to clutter the aspx pages.
 
if possible can you please throw some sample lines of how to acheive the same functionality in code-behind?
 
Thanks in advance

QuestionUsing Progress Bar with Master pages / within form or div tagmemberandre271122 Jan '07 - 5:45 
Hi & congratulations, this is a really nice piece of code.
 
Unfortunately I ran into some problems using this with Master pages and IE (operation is aborted with prompt, page does not show properly). I wanted to integrate the progress bar in some content pages that use a master page which uses a <form> tag inside (and a global <div> for layout reasons). Seems that initNotify() breaks when called within a <form> or a simple <div> tag. Did you came across this problem and do you have any hint?
 
Thx and keep up good work!
André
AnswerRe: Using Progress Bar with Master pages / within form or div tagmemberjuras924 Apr '07 - 8:47 
Yup, i need this on masterpage too Frown | :( Cant figure it out, how to run it on master...
GeneralRe: Using Progress Bar with Master pages / within form or div tagmemberDaniel Ballinger28 Aug '07 - 14:38 
I've had some success using this within a master page.
 
I did the following:
1. Make LoadingNotifier inherit from System.Web.UI.MasterPage.
2. Take the "(!IsCallback)" out checks out of LoadingNotifier.
3. Have your master page inherit from LoadingNotifier in the code behind.
4. Add initNotify between the body and form tags in the declarative part of the master page.
5. Add Notify("100", "Done"); between the form and body closing tags of the master page.
 
That was enough for my basic requirements. I had to perform some extra checks in the JavaScript for null objects and I added the ability to directly call completed().
 
If you wanted to call Notify within the ContentPlaceHolder and assuming your master page is called Foo.master:
 
<%
((Foo)Page.Master).Notify("50", "Half way there!");
%>

Generalphp loadermemberjonavanmona5 Nov '06 - 11:40 
Hi, this is exactly what i need for my site!
 
only i know whit about asp, i do know php.
could somebody translate it for me?
i think its not that much effort, but i just cant do it.
 
that would be VERY nice:P
 
thanks
GeneralExtended CSS used (off topic)memberpharaon_login7 Oct '06 - 13:07 
Hi,
 
First of all thank you for the article, it is quite usefull for meSmile | :) . Also I've noticed that you used some non-standard CSS attributes like "-moz-opacity: 0.75" and "filter: ...". Can you suggest any internet resource with information on these tags? Especialy for Mozilla/Gecko related _moz_... tags, I was googling quite a lot, but did not find anything usefull. Even mozilla oficial developers site has quite a brief description.
 
Thanks,
AnswerRe: Extended CSS used (off topic) [modified]memberShahin__8 Oct '06 - 6:56 
Hi Pharaon
 
What kind of description are you looking for?
 
filter : alpha(opacity=50); //IE
MozOpacity : 0.5; //Mozilla , Netscape
KhtmlOpacity : 0.5; //Safari , Konqueror
opacity : 0.5; //Opera and CSS3 Browsers
 
Hope this helps!

 

-- modified at 15:03 Sunday 8th October, 2006
 
Rebuild all succeeded!

QuestionDisplay the loading status during Page_Loadmembersithwad3 Oct '06 - 0:04 
"To display the loading status during Page_Load or other events which are processed prior to sending the page to the client, you can directly write your status message to the Response object and call the Flush method. When the page is completed at the client, you should clean up your status messages"
 
Can anyone help or give an example on how to do this? I can't get it to work!

AnswerRe: Display the loading status during Page_LoadmemberShahin__3 Oct '06 - 15:42 
What is it exactly that you can get it to work?
 
Rebuild all succeeded!

GeneralRe: Display the loading status during Page_Loadmembersithwad3 Oct '06 - 22:29 
Sorry, the above code works fine but I was trying to get the the progress bar to work on page load. You say its possible but I couldn't get it to work.
 
Basically I have a page that has to loop through folders and grab the file sizes. This loop occurs on the page load and while it is doing this it would be great to have a progress bar shown while the code is getting the file sizes.
 
Also I have a .net 2.0 wizard that gathers data, the last page of the wizard takes all the input and stores it in a database, contacts the bank and does some other stuff. This is done on the Wizards last page onactivate sub and it would be nice to have a progress bar shown while the code executes.
 
Just wondering if someone could help me with an example of running your progress bar before the page loads if this is at all possible.
 
Many thanks
GeneralRe: Display the loading status during Page_LoadmemberShahin__4 Oct '06 - 17:53 
There are many ways you can do this. In most of the cases it is not really worth it to go all the way to the client just to update some percentages because by the time you get to the client the delay is resolved. What you can do is just showing a message or a picture indicating that you are processing the request. In your case a quick workaround to use LoadingNotifier class is to try refactoring your code out of the Page_Load event and call it in the context of your page after you initialized the progress bar. It may get tricky if you have non- declarative data binding, so make sure everything is synchronized.
 
Cheers!

 

 
Rebuild all succeeded!

Generalgreat jobmembervik202 Oct '06 - 18:58 
THis is a great job.
 
Vikram
http://www.vikramlakhotia.com
QuestionASP.Net with VB.Net versionmemberCatMark1 Oct '06 - 21:30 
Hi!,
 
Do you have the converted vb.net code?
 
Thanks
AnswerRe: ASP.Net with VB.Net versionmemberShahin__2 Oct '06 - 8:55 
This is mostly Javascript and CSS. You don't need to convert them in VB.NET. If you are concerned about the LoadingNotifier class, it pretty much translates to VB.NET the way it is. As a matter of fact a very similar piece of code would do the same job in PHP, JSP etc.
 

 

 
Rebuild all succeeded!

AnswerRe: ASP.Net with VB.Net versionmemberdacoty4 Oct '06 - 9:24 
CatMark,
below is the converted class to VB. not that it matters much, but here it is( i called mine loader)
 

Imports Microsoft.VisualBasic
Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'@ shahin@themorningoutline.com provided this UNDER GNU GPL
'@ For more inforamtion visit www.themorningoutline.com
' VB Port by David Coty - for instructional use only.
' please refer to the original author, shahin@themorningoutline.com for more details
' this code was NOT ported with any converters. use at your own risk
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Public Class loader ' change this class to whatever name you want
Inherits System.Web.UI.Page
 
Public Sub InitNotify(ByVal strSplash As String)
 
' Only do this on the first call to the page
'ADDL NOTE: you can possibly do this with ClientScript.RegisterClientScriptBlock
 
If (Not IsCallback) And (Not IsPostBack) Then
Response.Write(String.Format("<script type='text/javascript' src='scripts/loadingNotifier.js'></script><script language='javascript' type='text/javascript'>initLoader('{0}');</script>", strSplash))
'update the client
Response.Flush()
End If
 
End Sub
 
Public Sub Notify(ByVal strPercent As String, ByVal strMessage As String)
If (Not IsCallback) And (Not IsPostBack) Then
'run the setProgress routine
Response.Write(String.Format("<script language='javascript'
type='text/javascript'>setProgress({0},'{1}'); </script>", strPercent, strMessage))
'update the client
Response.Flush()
End If
End Sub
 
End Class
 
---- you use the class the same way in a web project but just inherit loader on the page.
HTH - David
GeneralRe: ASP.Net with VB.Net versionmemberShahin__4 Oct '06 - 17:38 

Very good David. About your comment on using ClientScript object, the RegisterClientScriptBlock and RegisterStartupScript methods will not work with the Notify method because of the position where the scripts are written to the HTML document. Also writing to the Response object is faster than dealing with ClientScript object. ClientScript object is very handy but not here!
 
Cheers!
 
Rebuild all succeeded!

GeneralRe: ASP.Net with VB.Net versionmemberdacoty5 Oct '06 - 2:45 
I noticed that when i first tried it - i got the initNotify method to work but the Notify Method was a bust because of the HTML position (i got a "can't modify controls in <%%>" error)
 
I'm still new to asp.net. i'll figure all this out someday Smile | :)
 
-David
QuestionRe: ASP.Net with VB.Net versionmemberdavidswift16 Aug '07 - 6:29 
Thanks David but how do I inherit the loader from my page source as I already have a statement like this -
 
<%@ Page language="VB" Autoeventwireup="False" Codepage="MyPage.aspx.vb" Inherits="Performance.MyPage" %>
 
(Performance is a namespace for the whole web project)
Regards
Dave
AnswerRe: ASP.Net with VB.Net versionmemberdacoty1 Oct '07 - 9:09 
hi dave,
i just saw this comment now ( it's October 07)
 
well, to call this code from a current aspx page, basically just take the code and copy it into an empty class file( name is something like loaderclass or whatever) and just define it in your project manually:
 
dim myLoader as new loaderclass
 
myloader.initNotify("blah")
 
A little late, but i hope it helps!
david
 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 1 Oct 2006
Article Copyright 2006 by Shahin__
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid