Tuesday, March 24, 2009

The loading gif problem (.NET)

If you've ever felt the need to use a loading gif , you may have run into a few problems.

Displaying the gif before the rest of page finishes loading isn't as simple a task as you would think. The best way I've found to do this is by dynamically writing javascript as the very first instructions of your Page_Load.

Response.Write("<div id="'mydiv'"> ")
Response.Write("Loading data...<img src="loading.gif" />")
Response.Write("</div>")
Response.Write("<script> var mydiv = document.getElementById('mydiv');</script>")
Response.Write("<script language="javascript">")
Response.Write("function StartShowWait(){mydiv.style.display = 'block';}")
Response.Write("function HideWait(){mydiv.style.display = 'none';}")
Response.Write("StartShowWait();</script>")
Response.Flush()


This basically creates a div tag which stores your loading message and the gif. The StartShowWait() function is called, which displays your loading gif and the Response.Flush() function renders this javascript code to your client before the rest of the page finishes loading. If you don't call Response.Flush(), your javascript code will sit on the server until the page is completely loaded.

In the HTML of your page, make sure you include the following javascript snippet to hide the loading gif once the requested page is completely loaded:

<script lang="javascript">
HideWait();
</script>


So are we done now? Depends on whether you want to do some more processing of data and redirect to another page. If you're using .NET, calling:

Response.Redirect("foo.aspx")

You will get a System.Web.HttpException: Cannot redirect after HTTP headers have been sent.

To overcome this, simple call another snippet of javascript to redirect the page and flush the response again:

Response.Write("<script language="javascript">location.href='foo.aspx';</script>")
Response.Flush()


Hopefully this will alleviate some headaches from trying to execute this simple task.

No comments: