Thursday, April 09, 2009

Referencing jQuery on a masterpage without breaking intellisense

If you are like me, you were pretty excited when Microsoft added support for jQuery to intellisense in visual studio. I am not going to go into how this is accomplished. If you would like details you can read Scotts blog here.

The Problem
When referencing jquery through a masterpage, you are vulnerable at runtime to the path of the content page. So if you keep your masterpages in a folder like "/Masters" but the content page you are using is in the root, a jquery path like this won't work:

<script src="../js/jquery-1.3.2.js" type="text/javascript"></script>

Intellisense works fine with this, but at runtime the path is wrong when using the content page in the root. To get the correct path at runtime we can do something like this:

<script src="<%= VirtualPathUtility.ToAbsolute("~/js/jquery-1.3.2.min.js") %>" type="text/javascript"></script>

With that reference we get the correct reference at runtime, but we get no intellisense.

The Solution
Until this problem is fixed by Microsoft, we need to use the best of both worlds. A static reference for the IDE, but a dynamic reference at runtime. To do this we use a condition on the reference that we don't want at runtime, like this:

<script src="<%= VirtualPathUtility.ToAbsolute("~/js/jquery-1.3.2.min.js") %>" type="text/javascript"></script>
<% if (this == null) { %>
    <script src="../js/jquery-1.3.2.js" type="text/javascript"></script>
<% } %>

You can replace the "this == null" with a simple "false" but you will get unreachable code warnings. You just need anything that always evaluates to false. This works great and has very little overhead in your page. I am happy that Microsoft added intellisense support for jQuery, now they just need to finish it so we don't have to use kludges like this.

2 comments:

  1. That's a great trick. Thanks for sharing

    ReplyDelete
  2. Works great. Thanks a bunch!

    ReplyDelete