Add Javascript to page OnLoad event

I used to add start up javascript to a page dynamically by assigning it to body tag OnLoad attribute. But this approach will get in trouble because it runs before all other web elements are rendered. Also it will need to set runat=”server”.

ASP.NET provide a better approach and I discover it just recently.

In your code-behind

Page.ClientScript.RegisterStartUpScript(this.GetType(), "functionName", "TheScript", true);

This function will put your script at the end of that page and run after the page is completely loaded.