简体   繁体   中英

User Controls and JavaScript and Master Pages

Consider the following situation:

There is a master page with a contentPlaceHolder for all javascript...

for speed issuses this section is at the bottom of the page.

my user control generates some javascript that make use of some references in the master page javascript (Jquery library)

so, if my user control is rendered before the master page javascript, it won't work.

and this is my question:

how do I make some javascript code block inside my .ascx file to be rendered to the asp:Content JavaScript in the .aspx page

or maybe my all thinking is worng?

Thanks!

See if this works for you:

Where in the "bottom" of the Master Page? If you move it inside the closing server-side form control and use ClientScript.RegisterStartupScript in your user control, it will inject that script of your control "before the closing <form/> tag" (which will be after your your static script call).

Master Page - right above the closing server-side ASP.Net </form> :

....
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js "></script>
</form>

Content Page (nothing special):

<%@ Register src= ....

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
    <uc1:jscript_inject ID="jscript_inject1" runat="server" />
</asp:Content>

User Control:

protected void Page_Load(object sender, EventArgs e)
{
    Page.ClientScript.RegisterStartupScript(this.GetType(), "foo", @"alert('foo');", true);

}

This is how its rendered (HTML view source in browser):

<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js "></script>

<script type="text/javascript">
    //<![CDATA[
    alert('foo');//]]>
</script>
....
</form>

As advertised, alert('foo'); is below the "pre-defined" jq cdn call....

Cheers useful. Interestingly this works for Page.ClientScript.RegisterStartupScript but not Page.ClientScript.RegisterClientScriptInclude , and instead the 'include' gets added to the top of the form.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM