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

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

<head runat="server">
  <link href="https://stackoverflow.com/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).

Leave a Comment