0

I am developing a jQuery plugin which needs to load other files relative to the same directory in which my 'plugin.js' file is located. Is there a way to do this?

3 Answers 3

1

One way to achieve this is to loop through all $('script') elements, identify the one that represents your plugin inclusion, and extract the path. Of course this might not be reliable as the consumer of your plugin might have renamed your .js file.

Actually what you have is a pretty weird requirement. Can't you simply describe in the documentation of the plugin which scripts need to be included or simply pass the relative url as argument to your plugin? For example many jQuery plugins take a url as parameter so that the consumer can specify where did he put other required scripts. This allows for the consumer more flexibility on the location of those external scripts.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that makes sense. I wanted to make the plugin more re-usable in that the loaded scripts would always be relative to the location of the plugin (same level or sub-dir). If the plugin is going to load non-js scripting files (.cfm in my case), then I suppose I can always make that an option to the plugin. Just as re-usable, but one more option to set. It would be nice to have a default if a path is not specified, but then it's the same problem, I would want the default to be relative to the plugin.js location. I will try looping through the script elements to see if I can set that.
1

Always use a "/" in front of the path you are trying to locate. A "/" means search at the root directory for instance:

<img src="images/image.png"> // Will search for a directory inside the current directory.
<img src="/images/image.png">      // Will search for a directory in the "Root" path.

The first example searches for a directoy relative to the current directory, the 2nd example searches for a directory located in the root of the hosted site.

Comments

0

You have to be sure your script is called as the first one on the page

var scripts = document.getElementsByTagName("script");
var thisScript = scripts[0];
var thisScriptsSrc = thisScript.src;

it's src of an actual javascript and you can do whatever you need with that

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.