Question: I have written a web app where the JS file lots of relative calls to other files. This has worked up to this point but now I am using this js file from pages in different directories and I am getting errors with the paths. This web app will be installed on lots of different hosts so I don't know if absolute paths will work as I won't know where it is installed. I also don't want to junk up the js with lots of prepended variables in my paths (but might have to).

I would LIKE the js paths to be relative to the js file itself and not the document opening it... is there a way to set a default root directory within a js file?

```
$.ajax({
    type: "POST",
    url: "inc/alert.php",
    success: function(msg){
        if(msg){
            window.location.href = 'inc/logoff.php?timeout=true';
         }
    }
});

```

This is my file structure, but I don't know where it will be installed or what the webapp folder will be called:

`/random-folder/web-app/inc/script.js`

And until now all my files using the js were in the "web-app" folder... but now I have other pages calling it in different folders and all of the paths are broken. Is there a way to do this? Or is there at least a way to **get the path of the js file itself**?

Thanks in advance for any help...

Answer: 
You can find the JS file's path by checking the `src` attribute on its `<script>` tag in the current document.

HTML:

```
<script src="/some/random/path/main.js"></script>

```

jQuery:

```
var scriptFilename = 'main.js';
var rootPath = ''; // Will contain the path to your file

$('script').each(function() {
    var $script = $(this);

    if ($script.attr('src') && $script.attr('src').indexOf(scriptFilename) > -1) {
        rootPath = $script.attr('src').split(scriptFilename)[0];

        return false;
    }
});

```
It is not possible to get the absolute path, for two reasons:

* JS is run on the client side
* The JS path is always relative to:
	+ The HTML page (`scripts.js` in `xyz.com/test/index.php` => `xyz.com/test/scripts.js`)
	+ The server document root (`/scripts.js` in `xyz.com/test/index.php` => `xyz.com/scripts.js`)

As a solution, you might want to:

* Either load your JS from a PHP, eg: `<script type="text/javascript" src="scripts.php"></script>`
* Or, prior to loading your scripts file, load a config file same as option 1, eg:
`<script type="text/javascript" src="config.php"></script><script type="text/javascript" src="scripts.js"></script>`