8.29.2012

RegisterClientScriptBlock vs RegisterStartupScript

Difference between Page.RegisterClientScriptBlock and Page.RegisterStartupScript

S.No Page.RegisterClientScriptBlock Page.RegisterStartupScript
1 RegisterClientScriptBlock places the script at the top of the page right after the starting 'form' tag . RegisterStartupScript places the script at bottom of page right before the ending 'form' tag.
2
The code cannot access any of the form's elements because, at that time, the elements have not been instantiated yet.
The code can access any of the form's elements because, at that time, the elements have been instantiated.

3
RegisterClientScriptBlock is meant for functions that should be "available" to the page. For this they are rendered at the start of the HTML file. In this case the page content will be blocked.

RegisterStartupScript is meant for commands that should execute on page load (at the client), so that page needs to be available for the script. This script is rendered at the end of the 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 goes here");

Example for RegisterClientScriptBlock:

if (!Page.IsClientScriptBlockRegistered("CH"))

Page.RegisterClientScriptBlock("CH", "script goes here");


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.

No comments:

Post a Comment