ClientScript.RegisterStartupScript: script injected, but not executed

This was one weird mystery. I have used ASP.NET’s method ClientScript.RegisterStartupScript countless times to inject client-side JavaScript into page’s markup from the server-side code and it always worked perfectly. This time I created a very basic page from scratch:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>My Page</title>
    <script type="text/javascript" src="script1.js" />
    <script type="text/javascript" src="script2.js" />
    <script type="text/javascript" src="script3.js" />
</head>
<body>
    <form id="xfrmMain" runat="server">
    </form>
</body>
</html>

And then injected client-side script into it:

ClientScript.RegisterStartupScript(Me.GetType, "JSCode", "ProcessData();", True)

where ProcessData() is function from one of the scripts, loaded in the HEAD tag. The script injected just fine, I got a beautiful insert at the bottom of the rendered page:

<script type="text/javascript">
//<![CDATA[
ProcessData();//]]>
</script>

The problem was – it didn’d do squat – the script did not execute. Why?

Million dollar question. Googling didn’t help, there were a lot of solutions for scenarios wherw the script didn’t get injected, but once it was on the page – it always executed. I replaced the custom function call with a simple alert, thinking something might be the matter with the way scripts are loaded – it didn’t fire.

Finally looking back at HTML markup I noticed something different about the scripts are loaded. The tags are self-closing. But this shouldn’t be a problem, right? If element contains just attributes and no data – this shouldn’t cause any issues? Well, apparently in case of SCRIPT tag – WRONG! It didn’t throw any errors, simple did not execute the scripts (even the ones that has nothing to do with loaded JS).

When I changed script loading part to:

<script type="text/javascript" src="script1.js"></script>
<script type="text/javascript" src="script2.js"></script>
<script type="text/javascript" src="script3.js"></script>

function created by ClientScript.RegisterStartupScript executed.

Moral: Always close your script tag with closing tag.

Leave a Reply

Your email address will not be published. Required fields are marked *