Search This Blog

Friday, October 26, 2012

jQuery error: "$ is undefined"

When using Visual Studio 2010 and coding in ASP.NET where I'm using one of the various jQuery plug-ins (a datepicker, the BlockUI page blocker utility, or the jQuery validation tools) I'll occasionally get the JavaScript error featured in the title -- it simply means that the page fired up and it couldn't resolve the "$" synonym for "jQuery."

Invariably I'll check and make sure that I've got the jQuery code "included" in the web page (which I do) but if I look at the page using Firefox "Firebug" I'll see that something will have hosed up the syntax of the include statement (based on the browser, whether I'm using master pages, nested master pages, etc.).

Being lazy I like to include files by dragging them from the "Solution Explorer" pane of Visual Studio right into the ASP.NET/HTML code.  I always hope that VS2010 will just "figure out" the right syntax for me, and so long as I'm not using master- or nested-master pages I'm generally right.

Once masterpages are introduced, though, things get screwed up.

Here's a syntax solution I've found that seems to work pretty well:

Rather than:

<script src='~/scripts/jquery-1.8.2.js' type="text/javascript"></script>

I use:

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

It seems to circumvent the path-naming-weirdness introduced by ASP.NET-masterpage-wrapping.

No comments: