How to use external js file in ScriptManager.RegisterStartupScript?

user1178399 picture user1178399 · Mar 29, 2012 · Viewed 16.9k times · Source

i have a control which is on update panel. i want my javascript code run every time the updatePAnel is updated.

i use something like this:

ScriptManager.RegisterStartupScript(this, GetType(), "my_script", "runFunction();", true);

the problem is that my js code is huge and i want to place it in js file and use it from file. what should i change in my code ?

Answer

Raphael picture Raphael · Mar 29, 2012

You could use the ScriptManager.RegisterClientScriptInclude method:

ScriptManager.RegisterClientScriptInclude(
    updatePanel,
    updatePanel.GetType(),
    "a_key",
    "myScript.js"
);

Note that this method will render your script early in the HTML, so your script should not rely on the order scripts are rendered on the page.

More about this method at http://msdn.microsoft.com/pt-br/library/bb337005.aspx

But if your script depends on some other script, a better option is to use the ScriptManager.RegisterStartupScript method, but instead of passing the script body as a parameter, you pass the entire <script> tag with your script's address:

ScriptManager.RegisterStartupScript(
    updatePanel,
    updatePanel.GetType(),
    "a_key",
    "<script type='text/javascript' src='my_script.js'></script>",
    false
);

Note that the last parameter, which sets the addScriptTags flag, is set to false, allowing you to render the entire tag with the src attribute defined.