Relative Paths in Javascript in an external file
Solution 1
JavaScript file paths
When in script, paths are relative to displayed page
to make things easier you can print out a simple js declaration like this and using this variable all across your scripts:
Solution, which was employed on StackOverflow around Feb 2010:
<script type="text/javascript">
var imagePath = 'http://sstatic.net/so/img/';
</script>
If you were visiting this page around 2010 you could just have a look at StackOverflow's html source, you could find this badass one-liner [formatted to 3 lines :) ] in the <head />
section
Solution 2
get the location of your javascript file during run time using jQuery by parsing the DOM for the 'src' attribute that referred it:
var jsFileLocation = $('script[src*=example]').attr('src'); // the js file path
jsFileLocation = jsFileLocation.replace('example.js', ''); // the js folder path
(assuming your javascript file is named 'example.js')
Solution 3
A proper solution is using a css class instead of writing src in js file. For example instead of using:
$(this).css("background", "url('../Images/filters_collapse.jpg')");
use:
$(this).addClass("xxx");
and in a css file that is loaded in the page write:
.xxx {
background-image:url('../Images/filters_collapse.jpg');
}
Solution 4
Good question.
When in a CSS file, URLs will be relative to the CSS file.
When writing properties using JavaScript, URLs should always be relative to the page (the main resource requested).
There is no tilde
functionality built-in in JS that I know of. The usual way would be to define a JavaScript variable specifying the base path:
<script type="text/javascript">
directory_root = "http://www.example.com/resources";
</script>
and to reference that root whenever you assign URLs dynamically.
Solution 5
For the MVC4 app I am working on, I put a script element in _Layout.cshtml and created a global variable for the path required, like so:
<body>
<script>
var templatesPath = "@Url.Content("~/Templates/")";
</script>
<div class="page">
<div id="header">
<span id="title">
</span>
</div>
<div id="main">
@RenderBody()
</div>
<div id="footer">
<span></span>
</div>
</div>
Nate
Dad. Geek. Gamer. Web developer. Cloud user. Old Car enthusiast. Blogger.
Updated on January 28, 2020Comments
-
Nate over 4 years
So I'm running this javascript, and everything works fine, except the paths to the background image. It works on my local ASP.NET Dev environment, but it does NOT work when deployed to a server in a virtual directory.
This is in an external .js file, folder structure is
Site/Content/style.css Site/Scripts/myjsfile.js Site/Images/filters_expand.jpg Site/Images/filters_colapse.jpg
then this is where the js file is included from
Site/Views/ProductList/Index.aspx $("#toggle").click(function() { if (left.width() > 0) { AnimateNav(left, right, 0); $(this).css("background", "url('../Images/filters_expand.jpg')"); } else { AnimateNav(left, right, 170); $(this).css("background", "url('../Images/filters_collapse.jpg')"); } });
I've tried using
'/Images/filters_collapse.jpg'
and that doesn't work either; however, it seems to work on the server if I use'../../Images/filters_collapse.jpg'
.Basically, I want have the same functionallity as the ASP.NET tilda --
~
.update
Are paths in external .js files relative to the Page they are included in, or the actual location of the .js file?
-
Nate over 14 yearsI ended up doing this, except I use Url.Content to generate the value for
imagePath.
Thanks! -
Chev over 13 yearsHaha I did the same thing, then came back and read your comment nate.
-
daniloquio over 12 yearsThis works but it is also definetively a workaround, not a proper solution. @schory's answer gave me the solutions to OP's problem.
-
daniloquio over 12 years$("#FkngDiv").load(jsFileLocation+"../FkngFolder/FkngPage.aspx") Worked like a charm for me. I'm using it this way to go back one folder level and then I just point to my desired path.
-
RickAndMSFT about 12 yearsHard coding the root doesn't work on your dev box, test server, etc.
-
RickAndMSFT about 12 yearsThis doesn't work on test/dev machines. Why would you hardcode the path?
-
Juraj Blahunka about 12 yearsyou can always output your domain name or localhost path based on your configuration (dev/prod) dynamically
-
yitwail almost 12 yearsvery good answer. I'd change the
.replace
expression tojsFileLocation.replace(/example\.js.*$/, '')
in case there's a query string like a version number after the.js
-
GraehamF almost 11 yearsI used
Url.Content("~")
to get the Application root. hth -
Reza over 10 yearsThis doesn't work if I'm using a non-css attribute. For example:
<img src="/codes/imgs/a.png">
. I can't set this src attribute by css. -
Hutjepower almost 9 yearsYou dear sir, are my newest hero! Used this solution to find my css path on the server in an ASP.NET MVC Application, which is dynamically loaded from a folder one way sideways from my javascript folder...
-
Zia Ul Rehman Mughal over 8 yearsI don't know why your answer got downvote. This is what worked for me after hours of struggle... (Y)
-
JeanValjean almost 8 yearsI also like to do
var imagePath = window.location.protocol + "//" + window.location.host + "/"
-
user1566694 over 6 yearsI think because this points to servername/js rather than servername/applicationname/js, which I think is no different from "/js"