What is the Difference Between RegisterStartupScript() Method and RegisterClientScriptBlock() Method?

What is the Difference Between RegisterStartupScript() Method and RegisterClientScriptBlock() Method?

Both, RegisterStartupScript() method and RegisterClientScriptBlock() method will inject Javascript code that will fire during start up of subsequent postback.

The RegisterClientScriptBlock method inserts the client-side script immediately below the opening tag of the Page object’s element. The code cannot access any of the form’s elements because, at that time, the elements haven’t been instantiated yet.

The RegisterStartupScript method inserts the specified client-side script just before the closing tag of the Page object’s element. The code can access any of the form’s elements because, at that time, the elements have been instantiated.

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 diplayed first and then script will run.

The choice of which method to use really depends on the “order” in which you want your script to be run by the browser when rendering the page.

C#  code

if (!Page.IsStartupScriptRegistered("CH"))
Page.RegisterStartupScript("CH", "<script>alert('Hello Friend');</script>");
if (!Page.IsClientScriptBlockRegistered("CH"))
Page.RegisterClientScriptBlock("CH", "<script>alert('Hello Friend');</script>");

3 thoughts on “What is the Difference Between RegisterStartupScript() Method and RegisterClientScriptBlock() Method?

  1. Elisa

    Hey There. I discovered your weblog using msn. That is an extremely smartly written article. I’ll make sure to bookmark it and come back to learn more of your helpful information. Thank you for the post. I will definitely comeback.

  2. Serena

    Hello, this weekend is nice in favor of me, because this time i am reading this impressive educational paragraph here at my residence.

Comments are closed.