The RegisterStartupScript method is similar to the RegisterClientScriptBlock method. The major difference is that the RegisterStartupScript puts the script at the foot of the ASP.NET page as opposed to the top. The RegisterStartupScript method uses the same constructors as the RegisterClientScriptBlock method:
- RegisterStartupScript (type, key, script)
- RegisterStartupScript (type, key, script, script tag specification)
So what difference does it make to register the script at the foot of the page as opposed to the top? A lot, is the answer!
If you have JavaScript working with one of the controls on your page, you will not want your Javascript function to fire before the control is placed on the screen if it requires that control, therefore you should use the RegisterStartupScript method instead of RegisterClientScriptBlock.
For example, the below code listing creates a page that includes a simple control which contains a default value of ASP.NET 101.
<asp:TextBox ID="txtBox1" Runat="server">Hello ASP.NET</asp:TextBox>
Therefore use RegisterStartupScript to place a script on the page which uses the value in the txtBox1 control, as shown below:
protected void Page_Load(object sender, EventArgs e)
{
string myScript = @"alert(document.forms[0][’txtBox1’].value);";
Page.ClientScript.RegisterStartupScript(this.GetType(),
"MyScript", myScript, true);
}
This puts the JavaScript function at the foot of the ASP.NET page, so when the JavaScript actually starts, it can find the txtBox1 control and works as planned.