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!

1 comment:

  1. Do you need a financial help? Are you in any financial crisis or do you need funds to start up your own business? Do you
    need funds to settle your debt or pay off your bills or start a good business? Do you have a low credit score and you are
    finding it hard to obtain capital services from local banks and other financial institutes? Here is your chance to obtain a financial services from our company. We offer the following finance to individuals-
    *Commercial finance
    *Personal finance
    *Business finance
    *Construction finance
    *Business finance And many More:
    and many more at 2% interest rate;
    Contact Us Via Email:bullsindia187@gmail.com

    ReplyDelete