Improving performance is all about finding and removing bottlenecks. In many web applications, the bottleneck is one slow piece of the page. More specifically, it's the work that happens on the server to enable that one piece that's slowing down the application.
For example, you might have a page that displays an article along with links to related content. The article is quick to load, but those related links require a query across several databases and then an expensive merge step. This means that while your users are sitting at a blank page twiddling their thumbs, the article (which is what they want) is ready to go but stuck on the server waiting for those related links (which they don't yet care about).
This problem leads a lot of ASP.NET AJAX developers to ask how they can use the UpdatePanel to do a delayed load of part of the page. The most common answer I've seen on blogs and on the forums is to use the Timer control set with a short interval. The idea is that you render nothing in the UpdatePanel originally, and then in the timer's OnTick handler, you fill in the missing data.
Here's an example:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" />
<asp:Timer ID="timer" runat="server" Interval="1" OnTick="DelayedLoad" />
</ContentTemplate>
</asp:UpdatePanel>
And in the codebehind:
protected void DelayedLoad(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(2000);
Label1.Text = "Stuff that took a long time to load.";
timer.Enabled = false;
}
I believe this is the best solution for most situations. For comparison, here are some other possibilities:
- Client-side code that runs via
Sys.Application.add_load() that does __doPostBack('<%= UpdatePanel1.ClientID %>'). Just be careful to remove yourself via Sys.Application.remove_load() so you don't run again when the async postback finishes.
- Instead of using the timer's OnTick event, do the delayed loading in Page_Load behind an
if (IsPostBack). This is probably the simplest technique to make sure you're loading the data any time you need it. Just be aware that now on every async postback on the page, you're going to do the work we already decided was slow.
- Put the contents of that UpdatePanel on another page altogether, and fetch it asynchronously using Sys.Net.WebRequest or a web service call. See this post on ScottGu's blog for an example of how to do this. This is the most efficient solution if the controls are fully decoupled. If the controls do need to be in the same .aspx because they interact (via a trigger, for example) then this won't be an option.