3

有没有办法在正文标记结束之前注册脚本引用?我刚刚尝试过:

page.ClientScript.RegisterClientScriptInclude("jquery.widgets.js", page.ResolveClientUrl("~/js/plugins/jquery.widgets.js"));

但它在 ViewState 之后,在表单元素的开头注册文件。

4

2 回答 2

10

使用脚本管理器在 Page_Load使用LoadScriptsBeforeUI="False"属性时动态注册脚本,以确保在文档末尾注册脚本。

<body>
<form id="form1" runat="server">
    Some content here
    <asp:ScriptManager runat="server" ID="smScriptManager" LoadScriptsBeforeUI="False">
        <Scripts>

        </Scripts>
    </asp:ScriptManager>
</form>

然后在你的代码中

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    smScriptManager.Scripts.Add(New ScriptReference("~/Include/Site.js"))
End Sub
于 2013-01-16T11:33:01.403 回答
6

我所做的是在 MasterPage 的底部创建一个 ContentPlaceHolder(如果有的话)-

//Any scripts required on all pages, e.g. JQuery go before the content placeholder

<asp:ContentPlaceHolder ID="ScriptContentPlaceHolder" runat="server">
</asp:ContentPlaceHolder>
</body>

在单独的页面中,我将拥有 -

<asp:Content ContentPlaceHolderID="ScriptContentPlaceHolder" ID="PageScriptContent" runat="server">
     //Load script with application relative path
     <script src="<%= Page.ResolveURL("~/js/plugins/jquery.widgets.js") %>" type="text/javascript"></script>

     //Load script with HTML relative path
     <script src="/js/plugins/jquery.widgets.js" type="text/javascript"></script>
</asp:Content>

如果您确实需要有条件地从后面的代码中添加脚本,则可以使用Controls.Add将新文字或HtmlGenericControl添加到 ContentPlaceHolder 。

 HtmlGenericControl ScriptGenericControl = new HtmlGenericControl("script");
 ScriptGenericControl.Attributes.Add("type", "text/javascript");
 ScriptGenericControl.Attributes.Add("src", Page.ResolveURL("~/js/plugins/jquery.widgets.js"));
 PageScriptContent.Controls.Add(ScriptGenericControl);

或者-

 PageScriptContent.Controls.Add(new Literal(){ Text = string.Format("<script type='text/javascript' src='{0}'></script>", Page.ResolveURL("~/js/plugins/jquery.widgets.js")) };
于 2013-01-16T11:00:30.313 回答