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>");