Introduction
One of the UI best practices is to display a "Waiting to load" or "Loading" gif as the page load completes. This functionality is even more useful when your Page load has heavy data processing time.
Strategy
Since the Page Load functionality is called before document.ready
or windows.load
client side code, this task becomes a little tricky. I will be using ClientScript.RegisterStartupScript
along with jquery to achieve this functionality. Below is the outline of what we will do.
- Create a
Div
that holds Loading image/message with visibility as true
.
- Create Hidden Button.
- Move the Heavy duty code (time consuming code) from page load function to a Button click event.
- On button click, once the processing is completed, make the loading
div
invisible again.
- On page load, register the Script to call the button click event on
Ispostback false
.
So let’s get on with it!
Using the Code
Let us create the Div
, and Button
element.
<div id="divLoading"
runat="server" style="text-align: center">
<br /><br /><br /><br />
<br />
<img src="Images/Loading.gif"
alt="Loading..." /><br />
</div>
<asp:Button ID="btnPageLoad"
runat="server" Text="Page Load"
OnClick="btnPageLoad_Click"
Style="display: none" UseSubmitBehavior="false" />
Next step is to create Button
click event:
protected void btnPageLoad_Click(object sender, EventArgs e)
{
divLoading.Visible = false;
}
Now next, let us register the script at Page Load:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string script = "$(document).ready(function ()
{ $('[id*=btnPageLoad]').click(); });";
ClientScript.RegisterStartupScript(this.GetType(), "load", script, true);
}
}
And it's done!
Points of Interest
I tried a lot of things to get this functionality. Few of them are below which did not work for me.
Now this basically calls a settimeout
function from the body onload
event. Did not work!
- Second, I tried out using
window.load
function to hide the loading gif once the page is loaded. Problem is, the gif was loaded only after page load. Not much use.
- Third, I tried setting the gif visible at
document.ready
in JavaScript and then calling it to hide in body onload
function. Still did not work. Loading gif still appeared after page load.
It did not take me long to figure out that I will have to do something at Page load to make this work.
History
This is my first article on Code Project. So do make comments and give suggestions to make it better!