在body标记结束前注册脚本引用标记

时间:2013-01-15 07:50:46

标签: asp.net

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

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

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

2 个答案:

答案 0 :(得分:9)

使用脚本管理器在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

答案 1 :(得分:5)

我所做的是在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>

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

 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")) };