Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use external js file in ScriptManager.RegisterStartupScript?

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 ?

like image 824
user1178399 Avatar asked Dec 13 '22 03:12

user1178399


1 Answers

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.

like image 122
Raphael Avatar answered Feb 01 '23 23:02

Raphael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!