Wednesday, November 14, 2007

I thought You'd Like to Know

Difference between RegisterClientScriptBlock and RegisterStartupScript

Page.RegisterStartupScript (System.Web.UI)
Emits a client-side script block in the page response.
This method is now obsolete. Use ClientScript.RegisterStartupScript instead.

Page.RegisterClientScriptBlock (System.Web.UI)
Emits client-side script blocks to the response.
This method is now obsolete. Use ClientScript.RegisterClientScriptBlock instead.

A control can place a startup script on a page via the RegisterStartupScript method. You can also place a script block that needs to be explicitly called by other script code on the same page using the RegisterClientScriptBlock method.

The difference between the two methods is that that the latter goes in the top of the page (immediately below the opening tag of the Page's <form runat='server' /> element) and the former goes at the bottom (just before the closing tag of the Page's <form runat='server' /> element). This is important because inline script generally needs to go at the bottom so that the page objects exist before it executes. However, regular script (script methods that will be called based on other control's events) must go at the top in case a control is referencing it. For example, in an onClick event of a button, you would like to reference function foo(), and foo() was emitted via codebehind. The correct way of registering foo() is by using RegisterClientScriptBlock.

Note: as always, remember to include HTML comment tags (<!-- your script here -->) around your script so that it will not be rendered if the requesting browser does not support scripts.

No comments: