5

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 ?

1 Answer 1

14

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.

Sign up to request clarification or add additional context in comments.

3 Comments

i changed code according to Your advice, but strange thing, now i get error in my js file - Object expected. at he same time when i pass js code like a string its OK.
@user1178399, it seems like your script depends on other scripts that are being rendered after it (and, therefore, the objects you depend on are not created yet). See the complemented answer above to know what to do.
nice, at least your last explanation stopped me from further searching the net for a solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.