September 9th 2008

Moving jQuery File Reference to ASP.NET MasterPage

Tonight I decided to try moving my jQuery file out of all my individual files to an ASP.NET MasterPage since it is in a project that uses jQuery on every page. I ran into two gotchas that I thought I would share.

  1. Initially my script was placed below my head ContentPlaceHolder (see example code below) which works fine until you try and run any jQuery in that place holder on a page that references the MasterPage. This occurs of course since jQuery hasn’t been loaded by the time the function tries to run.

     <head runat="server">        
         <asp:ContentPlaceHolder id="head" runat="server">
         </asp:ContentPlaceHolder>  
    
         <script src="_scripts/jquery-1.2.6.min.js" type="text/javascript"></script> 
     </head>
    
  2. You have to be careful with the relative reference to the JavaScript file. If your page that references the MasterPage is not at the same directory level then things won’t work either. There is an easy way to fix this. You can use ResolveUrl. See the code below.

      <script src='<%=ResolveUrl("/_scripts/jquery-1.2.6.min.js" ) %>' type="text/javascript"></script>
    

Updated 02NOV08

  1. I ran into a new problem today. I received the following error “The Controls collection cannot be modified because the control contains code blocks (i.e. <% … %>).” What I found out was happening was if I tried to add a link to the javascript file for a plugin that I needed only for a particular page in the Head ContentPlaceHolder of that page then things wouldn’t work and I would get the error above. A search for the error led to this article which has more details http://www.aspnetresources.com/blog/code_blocks_inside_master_pages_cause_trouble.aspx. So the workaround is to use <%# %> instead of <%= %> and then call for data binding on page OnLoad with:

     protected override void OnLoad (EventArgs e)
     {
       base.OnLoad (e);
       Page.Header.DataBind ();
     }
    

Hopefully this might help someone that hasn’t run into these problems before.