Wednesday, December 23, 2009

The Difference Between RegisterStartupScript and RegisterClientScriptBlock

We have two different methods for placing JavaScript functions on an ASP.NET page—so what is the difference? The main difference is that the RegisterStartupScript method places the JavaScript at the bottom of the ASP.NET page right before the closing </form> element. The RegisterClientScriptBlock method places the JavaScript directly after the opening <form> element in the page. So what difference does this make? It can make quite a bit of difference as we will see.

For an example of this, here is a way to put focus on a text box on a page when the page is loaded into the browser—with Visual Basic .NET using the RegisterStartupScript method:

Page.RegisterStartupScript("Testing", "<script

  language=javascript>document.forms[0]['TextBox1'].focus();</script>")

This works all well and fine because the textbox on the page is generated and placed on the page by the time the browser gets down to the bottom of the page and gets to this little bit of JavaScript. But if instead it was written like this (using the RegisterClientScriptBlock method):

Page.RegisterClientScriptBlock("Testing", "<script

  language=javascript>document.forms[0]['TextBox1'].focus();</script>")

Focus will not get to the textbox control and a JavaScript error will be generated on the page

The reason for this is that the browser will encounter the JavaScript before the text box is on the page. Therefore, the JavaScript will not be able to find a TextBox1.

 

 

No comments:

Post a Comment