JQuery with MasterPage in ASP.NET

asp.netjquerymaster-pages

I'm trying to use JQuery with some asp.net pages, that use master pages, and I'm having problems with loading the JQuery javascript file.

When I include the file in the markup of the master page, it works just fine on pages that are in the same directory as the master page:

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

but that breaks for pages that aren't in the same directory as the master page. Master pages inherit the path of the page that includes them, so the relative path to the jquery .js file is different, for different pages. And, of course, I can't have different relative paths in the master file, because there's only one of them.

I could use an absolute path:

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

but that breaks if the website is installed as a virtual directory.

My next try was to use the "~" to indicate the root of the website:

<script src="~/jquery/jquery-1.4.2.min.js" type="text/javascript"></script>

But the script tag doesn't understand the ~".

So I tried to do it in the code-behind. From OnInit(), I tried:

string url = "~/jquery/jquery-1.4.2.min.js";
url = this.ResolveUrl(url);
Page.ClientScript.RegisterClientScriptInclude("jquery_js", url);

And that gives me errors when the JQuery javascript runs. I have some javascript in the markup of the page:

$(document).ready(function()
{
    ...
}

and I get "$" is undefined. I added an alert to the beginning jquery-1.4.2.min.js, and it's loading OK, but after this bit of javascript in the .aspx file has executed.

I tried ScriptManager.RegisterClientScriptInclude(), instead, with the same result.

Best Answer

You could either use:

<script type="text/javascript" src="<%= ResolveUrl("~/jquery/jquery-1.4.2.min.js")%>"></script>

Or possibly build a control which essentialy does the remapping for you:

<my:Script src="~/jquery/jquery-1.4.2.min.js" />

Or even register it with the ClientScriptManager, but it's best to put it in the page.