Monday, 4 May 2015

How to get relative path in javascript 1

Problem

We can't easily get relative paths in javascript as like server side scripts. We have use our own logic to get it. Hard coding server root path in javascript is really bad idea. So, We are going to get our server root path from already loaded resource.


Why I need this?

If you are going to do use redirection or want to load any other resource which is located another directory in your server root directory, you may need server root path. On that time you should need this.

Solution

 Assume, we are having "http://sampledomain.com" and our assets in webroot directory. consider we have an external javascript file called "sample.js", add id attribute to your script tag.

And simply get the location of your javascript file during run time using javascript by parsing the DOM for the 'src' attribute that referred it:

Now we can call getRootPath() function to get the server root path. So, by our example our javascript function getRootPath() will return "http://sampledomain.com"

We can also use this as webroot path by removing "webroot" string from the replace function. If we did this, we will get "http://sampledomain.com/webroot" from the returned string.


Have any doubt, feel free to comment here!