如何在ScriptManager中更改已注册脚本的顺序 [英] How to change the order of registered scripts in a ScriptManager
问题描述
在我们的母版页中,我们有一个ScriptManager
看起来像这样
Within our master page we have a ScriptManager
that looks something like this
<asp:ScriptManager ID="ScriptManager" runat="server" EnablePartialRendering="False" EnableScriptLocalization="true">
<Scripts>
<asp:ScriptReference Path="~/js/master.js" />
<asp:ScriptReference Path="~/js/jquery-min.js" />
</Scripts>
</asp:ScriptManager>
我正在通过以下操作在页面上的嵌套控件中注册其他脚本
I'm registering additional scripts in nested controls on pages by doing the following
protected override void OnPreRender(EventArgs e)
{
ScriptManager.RegisterClientScriptInclude(this, this.GetType(), "jquery-ui", "~/js/jquery-ui.js");
base.OnPreRender(e);
}
预期
- master.js
- jquery-min.js
- jquery-ui.js *
实际
- jquery-ui.js *
- master.js
- jquery-min.js
问题
是否可以更改注册脚本的加载顺序?
Question
Is there any way to change the order the registered scripts are loaded in?
-或-
是否至少可以确保在实际的ScriptManager
块中注册的脚本先于代码隐藏的注册脚本被注册?
Is it possible to at least ensure the scripts that are registered in the actual ScriptManager
block are registered prior to code-behind registered scripts?
推荐答案
深入研究ScriptManager
源代码后,我们可以做两个有用的观察:
After digging a bit into ScriptManager
source code we can make two useful observations:
-
添加到管理器的脚本会按顺序依次显示在集合
ScriptManager.Scripts
中(如果您很好奇-通过方法ClientScript.RegisterClientScriptBlock
,而不是在Render
方法或smth中),则会在页面上进行注册.那样).
Scripts added to the manager are registered on the page one by one in order they appear in the collection
ScriptManager.Scripts
(if you are curious - via methodClientScript.RegisterClientScriptBlock
, not in theRender
method or smth like that).
在标记中声明的脚本将在创建ScriptManager
对象时添加到集合ScriptManager.Scripts
中.
Scripts declared in the markup will be added to the collection ScriptManager.Scripts
upon ScriptManager
object creation.
因此有一种方法
确保在代码隐藏的注册脚本之前先注册在实际ScriptManager块中注册的脚本
ensure the scripts that are registered in the actual ScriptManager block are registered prior to code-behind registered scripts
是将控件中的脚本直接添加到ScriptManager.Scripts
集合中,而不是使用ScriptManager
类的静态实用程序方法.控件的代码示例如下:
is to add your scripts in controls directly into ScriptManager.Scripts
collection instead of using static utility methods of ScriptManager
class. Control's code sample follows:
protected override void OnPreRender(EventArgs e)
{
ScriptManager currentScriptManager = ScriptManager.GetCurrent(this.Page);
if (currentScriptManager != null)
{
ScriptReference scriptRef = new ScriptReference("~/js/jquery-ui.js");
currentScriptManager.Scripts.Add(scriptRef);
}
else
{
this.Page.ClientScript.RegisterClientScriptInclude(
this.GetType(), "jquery-ui", "js/jquery-ui.js");
}
base.OnPreRender(e);
}
一个小注意事项-从代码示例中可以看出,当页面上没有ScriptManager
时,我建议您处理这种情况.
One small note - as can be seen in the code sample I would recommend handle case when there is no ScriptManager
on the page.
这篇关于如何在ScriptManager中更改已注册脚本的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!