ASP.NET, XML, SQL and Javascript tips and tricks

Often there is a need to generate JavaScript instructions in server-side ASP.NET code and send them to the client for execution. But what if you need to run that server-generated JavaScript code within client Page Load event (here I am talking about ASP.NET AJAX pageLoad(sender, args) event, but it applies to generic body.onLoad event as well).
Let’s say you have the following JavaScript code:

In this code a global variable is declared and on Page Load event a reference to a DIV control is assigned to it. Now lets say on server side you perform some calculations or read data from the database and then want to assign that data to innerHTML property of that DIV:

Here I am using function to run JavaScript described in this post, but in this context it’s pretty much identical to ClientScript.RegisterStartupScript.

The problem with this approach is if server-generated code executed on client before the pageLoad event you will get an error, because g_oDiv variable is not initialized by that time. One way to try to delay execution is using setTimeout function:

This will delay execution of server-generated JavaScript code for 10 milliseconds giving pageLoad event a chance to run first. But this approach can produce inconsistent results.

A better approach is to generate full JavaScript function on server. This way the generated code doesn’t get executed at all unless this function is called. And we can place the call in client pageLoad event.

is this code work for ASP.NET 2.0 non-AJAX ? is there any namespace that I need to include, as the RunJavascript is not recognized ? and which section should the StringBuilder portion should be putting in ?

@Thinnakone
The code should work for standard “onLoad” event (the one you specify in <BODY onload=”onLoad()”> tag ).
RunJavaScript is a special function I wrote to take into account async postback from Infragistics control (the function is described in this post: http://codecorner.galanter.net/2009/07/28/injecting-client-script-into-infragistics-async-postback/) but a standard ASP.NET “Clientscript.RegisterStartupScript” function can be used instead.
And StringBuilder is used just before call to this function. The sequence is: StringBuilder is used to build the string with JavaScript code and then RunJavascript (or ClientScript.RegisterStartupScript) is used to send this code to the client.