views:

312

answers:

3

I am using ScriptManager.RegisterStartupScript to register calls to a large number of JS functions.

ScriptManager.RegisterStartupScript(this, this.GetType(), "Script1", "SomeScript1", true);
ScriptManager.RegisterStartupScript(this, this.GetType(), "Script2", "SomeScript1", true);
ScriptManager.RegisterStartupScript(this, this.GetType(), "EndScript", "EndScript", true);

When the HTML is rendered, it's adding them in order.

<script type="text/javascript">
//<![CDATA[
other functions calls..
SomeScript1();SomeScript2();EndScript();
//]]>
</script>

However, when I step through in debug mode, the execution of scripts are not in order (Ex: EndScript executes first before SomeScript1 or SomeScript2)

Doesn't ScriptManager.RegisterStartupScript gaurantee execution in the order it was added? If not, what are the alternatives (I want to always execute EndScript in the end)

+2  A: 

From the MSDN page for RegisterStartupScript:

Startup script blocks that are registered by using RegisterStartupScript are not guaranteed to be output in the same order in which they are registered. If the order of the startup script blocks is important, use a StringBuilder object to gather the script blocks in a single string, and then register them all as a single startup script.

After they're rendered to the page, the actual execution of the scripts is handled by the browser, and doesn't have anything to do with the ScriptManager control. Looking at the example you have posted, the browser should execute those in the order they're written. Could your EndScript function be called by something else on the page, as well? Also, if you're using any sort of callbacks, then the timing of when the callback completes is indeterminate. Can you provide an example of the code that is in each of those scripts?

bdukes
But they are added in the correct order. Is the MSDN link implying that they will be added in the correct order but not executed in the order it was added? Unfortunately, I can't gather all the script blocks to a single string. Any other workarounds?
A: 

The script block added by the RegisterStartupScript method executes when the page finishes loading but before the page's OnLoad event is raised

you need to look into this article: http://msdn.microsoft.com/en-us/library/asz8zsxy.aspx

Muhammad Akhtar
Yes, but the order of execution is not the same as the order it was added
+1  A: 

The output you have shown is guaranteed to run in that order.

It is possible that EndScript begins executing before SomeScriptX() has completed their work if SomeScriptX issue calls to setTimeout from within their bodies.

Or, perhaps "other functions calls.." is invoking EndScript() somewhere deep.

Either way, if you can guarantee that ScriptManager is rendering that exact order in its output, then that is the order JavaScript will execute them in.

Crescent Fresh