javascript 如何在 ScriptManager.RegisterStartupScript 中使用外部 js 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9930352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 08:16:12  来源:igfitidea点击:

How to use external js file in ScriptManager.RegisterStartupScript?

c#javascriptscriptmanager

提问by user1178399

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

我有一个位于更新面板上的控件。我希望每次更新 updatePAnel 时都运行我的 javascript 代码。

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 ?

问题是我的 js 代码很大,我想将它放在 js 文件中并从文件中使用它。我应该在我的代码中更改什么?

回答by Raphael

You could use the ScriptManager.RegisterClientScriptIncludemethod:

您可以使用以下ScriptManager.RegisterClientScriptInclude方法:

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.

请注意,此方法将在 HTML 的早期呈现您的脚本,因此您的脚本不应依赖于脚本在页面上呈现的顺序。

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

有关此方法的更多信息,请访问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.RegisterStartupScriptmethod, but instead of passing the script body as a parameter, you pass the entire <script>tag with your script's address:

但是,如果您的脚本依赖于其他一些脚本,则更好的选择是使用该ScriptManager.RegisterStartupScript方法,但不是将脚本正文作为参数传递,而是使用<script>脚本地址传递整个标记:

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 addScriptTagsflag, is set to false, allowing you to render the entire tag with the srcattribute defined.

请注意,设置addScriptTags标志的最后一个参数设置为 false,允许您使用src定义的属性呈现整个标签。