473,396 Members | 1,590 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

How JavaScript can get its own File Path

I'm trying to get the pathname of the .js file that the currently-executing function resides in. This is useful if your .js file loads other assets within (or based on) the directory your .js file is in.


After being told by several folks it wasn't possible, I actually figured out a way (shown below), so
  1. I'm posting it so others may benefit, and
  2. You can tell me if there are any potential bugs.
  3. You can tell me if there's a better way.

Include the following snippet in the first line of your .js file:

Expand|Select|Wrap|Line Numbers
  1. var thisScript = (function(){
  2.     var ScriptID = "ScriptID" + Math.round(100000*Math.random());
  3.     document.write("<script id='"+ScriptID+"'></script>");
  4.     return document.getElementById(ScriptID).previousSibling.getAttribute("src");
  5. })()
  6.  
  7. alert(thisScript);
and thisScript will contain a string representing the filepath to the currently-executing .js file, ie "JavaScript/test.js".

Tested in IE 7, Firefox 2, Safari 3

HOW IT WORKS:
First off, we generate a random ID. Next, we use document.write to create a bogus <SCRIPT> tag in the DOM (we can't use DOM commands here because the page is still streaming and DOM doesn't fully exist)

That done, we now look for the bogus tag, knowing that its previous sibling *must* be the currently-executing <SCRIPT> tag. (Amazingly, even though DOM isn't fully written yet, this still works).

Finally, we just grab the src attribute of the current <SCRIPT>, and we have our answer. Any functions that reference the global thisScript will automatically know their own filepath.

If you are dealing with multiple JS files, just vary the name of thisScript (thisScript1, thisScript2, etc), or else reference thisScript within a closure function to capture its state at the time it was executed.

I wrapped the whole thing in a null closure, so the function and all variables it creates garbage-collect the moment it runs, to avoid stepping on any existing code. All that remains is the var you assigned along with its value.
Apr 21 '08 #1
5 8798
mrhoo
428 256MB
You can use dom methods as soon as the html element is read,
as long as you do not call anything by name that does not yet exist.

var scr=document.getElementsByTagName('script');
scr=scr[scr.length-1]
alert(scr.src || scr.text);

I cannot imagine the need for this- once loaded,
all the scripts become a single script, within the same window scope.
Apr 22 '08 #2
This is extremely useful if you're trying to load assets other than javascript that happen to be in the same directory as the script. This is particularly true if you're trying to get the same group of assets to load across multiple servers, and don't necessarily have control over the who|what|where factors.

For instance, I have a utility program written as several SWFs which are stored along with the support javascript that loads them and sends them information. The support js loads, and automatically knows where to look for the SWFs (based on its src attribute), rather than being explicitly told.

This means that installation is now simply "unzip this folder on your server and load the script" rather than "unzip and put the script here, but put the files over there, and now you have to tell the script where the files are" and all that nonsense. Developers only need to know that they need to load the .js file because it's able to locate the SWFs that it needs entirely on it's own. They don't even need to be AWARE there are other assets.

This has a side of effect of greatly increasing portability - the exact same script can now be used to load the assets, even if loaded on different pages and websites - even crossdomain - without being told where anything it needs happens to be.

This creates a modular, almost object-oriented approach with the physical folder structure, rather than a more traditional, "sorted-by-filetype" approach where "js files go here and swf go there and jpgs go..".

The folder containing all the js and other assets is now wholly self contained - it's a module. Assets such as support graphics, swfs, audio etc are now tied to their module, rather than tied to the webpage containing the module.
Apr 30 '08 #3
I like your way a little better, since it doesn't create the extra Script and avoids document.write, so I'll test to see how well it works on all major browsers.

Both approaches suffer a fatal flaw, though; they assume the currently-executing script hasn't already injected another script into the page, which is a dangerous assumption: both methods will pick up the wrong script, which may be sourced differently.

In that case, it may be necessary to (gag) actually walk the code to verify it's the right code... or put in a liner note saying "hey, call this first".

Additionally, neither version, I think, is going to work after the document stream has closed, ala Dojo/Prototype, although yours stands a better chance since it's just pure DOM. Ah well... more liner notes... :)
Apr 30 '08 #4
[quote=Arodicus]I like your way a little better, since it doesn't create the extra Script and avoids document.write, so I'll test to see how well it works on all major browsers. [quote]

Slight modification to your code:

Expand|Select|Wrap|Line Numbers
  1. var scr=document.getElementsByTagName('script');
  2. var src=scr[scr.length-1].getAttribute("src");
  3. alert(src);
... which now works great! Thankas for the input, this seems to be much better.

The use of getAttribute provides consistency across platforms. Under Mozilla browsers, scr.src returns a fully qualified URI, while IE returns a relative URI; getAttribute however always returns the exact attribute that was actually used, which could be significant for some parsing out the container ref as I suggested above.
Apr 30 '08 #5
tkamin
1
Expand|Select|Wrap|Line Numbers
  1. var scr=document.getElementsByTagName('script');
  2. var src=scr[scr.length-1].getAttribute("src");
  3. alert(src);
It seems that this solution might fail if the last script tag pulls an external JS file - like when the last script is a reference to Google Analytics (ga.js).
Oct 28 '11 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: Matt | last post by:
The user can select a file in the file open dialog using <input type="FILE">, but the user can also enter the full file path in the browse text box manually. My question is if there are JavaScript...
3
by: Matt | last post by:
Is there a way to use JavaScript to check if a file path exists? For example, user enter C:\eklrjlejr in a text box, and I want to check if the file really exists. Is there a way to use JavaScript...
3
by: Raed Sawalha | last post by:
I'm getting the file path via webservice using following code:- FileInfo fInfo = new FileInfo(filename); return fInfo.FullName; the return file backed as C:\test\images\1.jpg in application...
6
by: Naveen K Kohli | last post by:
I have couple of javascript files that need to be referenced for each content page. So I am trying to put them on Master page. The problem is that content pages are not on one level of the site. I...
3
by: Vibhu | last post by:
Hello All, I have a input box on the HTML page with the type set to file. What I want is that when the value changes in the file textbox, it should give me the full file path. I have even tried...
3
by: stephen | last post by:
Hi, I have a javascript file that I want to use on a button. If I have the javascript file in the same folder as the webform then it works for eg: /SampleApp/WebForms/TestForm.aspx but I...
7
by: Mike | last post by:
I need to load the WebForm JavaScript from my own location instead of the resource URL ( http://localhost/WebResource.axd? d=4vyf787asdY8c9h_cvayUuA2&amp;t=633236395245382000). Is there any way to...
3
by: NobodyImportant | last post by:
Hello everyone! I admit up front that I am new at this and have very little knowledge of JavaScript, but we have an asp web form that allows for the manipulation of letters our company regularly...
2
by: JohnLorac | last post by:
Hello, I'm trying to load and write file on local disc drive using signed javascript file. But I have experienced problem running this url: ...
3
by: Carlos Avrard | last post by:
Working with a simple directory/file tree display solution (http://abeautifulsite.net/blog/2007/06/php-file-tree/) I'm able to get the page to display properly, javascript works just fine as well,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.