Proper way to use JQuery when using MasterPages in ASP.NET?

Solution 1:

You would declare your main jQuery scripts within the master page, as you would normally:

<head runat="server">
  <link href="/Content/Interlude.css" rel="Stylesheet" type="text/css" />
  <script type="text/javascript" src="/Scripts/jquery-1.3.2.min.js"></script>
  <asp:ContentPlaceHolder ID="head" runat="server">
  </asp:ContentPlaceHolder>
</head>

And then any page specific JS files could be loaded within the Content controls that reference the Head ContentPlaceholder.

However, a better option would be to look into the ScriptManager and ScriptManagerProxy controls - these can provide you with a lot more control over the way your JS files are served to the client.

So you would place a ScriptManager control in you master page, and add a reference to the jQuery core code in that:

<body>
  <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
      <Scripts>
        <asp:ScriptReference Path="/Scripts/jquery-1.3.2.min.js" />
      </Scripts>
    </asp:ScriptManager>

Then, in your page that requires some custom JS files, or a jQuery plugin, you can have:

<asp:Content ID="bodyContent" ContentPlaceholderID="body">
  <asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server">
      <Scripts>
        <asp:ScriptReference Path="/Scripts/jquery.fancybox-1.2.1.pack.js" />
      </Scripts>
  </asp:ScriptManagerProxy>

The ScriptManager allows you to do things like control where on the page scripts are rendered with LoadScriptsBeforeUI (or better yet, after by setting it to False).

Solution 2:

I use this method.

<script type="text/javascript" language="javascript" src='<%=ResolveUrl("~/scripts/jquery.js") %>' ></script>

Just place it above your tag...

<asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>

Solution 3:

Alright use a different contentplaceholder for your script. It should look like this

<script type="text/javascript" src="myscript.js" />
<asp:ContentPlaceHolder ID="ScriptContent" runat="server">

</asp:ContentPlaceHolder>  

Place this tag at the bottom of your masterpage, close to the </body> tag. This will allow you add scripts on the masterpage and also on your pages as well. Make sure that your scripts are loading in the right order by viewing the page source and ensuring the HTML rendered in the right way. Good luck.

Oh one more thing, make sure jQuery and then FancyBox load up before any other js you may have out there or else it won't work. Javascript loads in the order it was called, jQuery must load first!