Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Difference between registerclientscriptblock and registerstartupscript
1. Difference between Page.RegisterClientScriptBlock and Page.RegisterStartupScript
S.No Page.RegisterClientScriptBlock Page.RegisterStartupScript
1 RegisterClientScriptBlock places RegisterStartupScript places the script
the script at the top of the page at bottom of page right before the
right after the starting 'form' tag . ending 'form' tag.
2 The code cannot access any of the The code can access any of the form's
form's elements because, at that elements because, at that time, the
time, the elements have not been elements have been instantiated.
instantiated yet.
3 RegisterClientScriptBlock is RegisterStartupScript is meant for
meant for functions that should be commands that should execute on page
"available" to the page. For this load (at the client), so that page needs
they are rendered at the start of to be available for the script. This
the HTML file. In this case the script is rendered at the end of the
page content will be blocked. HTML file. In this case the content of
the page will be diplayed first and then
script will run.
Example for RegisterStartupScript:
if (!Page.IsStartupScriptRegistered("CH"))
Page.RegisterStartupScript("CH", "<script>alert('Hello Friend');</script>");
Example for RegisterClientScriptBlock:
if (!Page.IsClientScriptBlockRegistered("CH"))
Page.RegisterClientScriptBlock("CH", "<script>alert('Hello Friend');</script>");
Note:
The choice of which method to use really depends on the "order" in which we want our script to be
run by the browser when rendering the page.
Take an example of a javascript function that populates a Textbox using a javascript function when
a page is loaded. If we use the RegisterClientScriptBlock method, the javascript function will give
an error. This is because our script is placed at the top of the page when it was loaded (when the
textbox was not even created). So how can it find the textbox and populate the values. So in this
case RegisterStartupscript should be used.
And, further updates on difference between questions and answers, please visit my blog @
http://onlydifferencefaqs.blogspot.in/