4

I've got an ASP.NET MVC application that uses jQuery. To load the js libraries, I reference them like this:

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

This works fine locally, but when I publish it to the server, it can't find the library. To get it to work, I have to change it to this:

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

Making this change allows it to work locally and on the server, but it gives me a warning that the file was not found. So I've got a couple of questions:

  1. How does the code work locally if I'm not referencing the correct library location?
  2. What can I put for a script path that will work everywhere and not throw a warning?

I know an answer to #2 is to store the libraries in some known absolute path, but I'm not ready to commit to that yet.

4 Answers 4

6

Try this:

<script type="text/javascript" src='<%= Url.Content("~/Scripts/jquery-1.3.2.min.js") %>'></script>

This will relativize the path to the root of your application regardless of whether it is at the top level or in a virtual directory. I actually developed a HtmlHelper extension that lets clean this up to:

<%= Html.Javascript( Url.Content( "~/Scripts/jquery-1.3.2.min.js" )) %>

Add the following to get intellisense. This needs the relative path to work, but gets excluded at runtime because the condition (always) fails.

<% if (false) { %>
     <script type="text/javascript" src="../../Scripts/jquery-1.3.2.vsdoc.js"></script>
<% } %>
1

As Andrew says, your directory structure is totaly different. Have you considered using google's load library to load Jquery for you from the closet location to the user?

1

Have you tried referencing the file from the root url? I.e. instead of "../../", which has to crawl up a directoy, use "/Content/Scripts/jquery-1.3.2.min.js". This would angnostic of your directory structure.

You should also consider using google to load jquery:

http://code.google.com/apis/ajaxlibs/

You'll get much better load times.

Mike

2
  • "/Content..." is not directory-agnostic; it will fail if the application is installed in a virtual folder. You need to use Url.Content ("~/Content...") in order to be truly directory-agnostic. Apr 8, 2009 at 14:47
  • Second the recommendation for using Google jQuery, because it's on a different domain the browser can load it at the same time as your other scripts. but it'll be nicely gzipped and miniiified
    – Tom
    Apr 8, 2009 at 14:59
1

The reason your code is working locally is because your local directory structure is different from your production directory structure.

That being said I believe that an absolute path to any external resources (javascript, images, and stylesheets) is best.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.