CoderZone.org

Category: >> JavaScript >> Automatically find location of javascript file Bookmark and Share

<< lastnext >>

Snippet Name: Automatically find location of javascript file

Description: What this does is find the location of a javascript file on the server when it's included via html.

Also see:
» Find All Elements By Class
» TABLESPACE: List tablespaces, fil...
» INDEXES: Alter Index Deallocate Un...
» INDEXES: Alter Index Allocate Exte...

Comment: This is very useful when used it in a reusable library. You can place the JS file anywhere on your server and allow the JS file itself to find were it's located and eventually load other js files relative to that path. This can save you having to do some ugly hard-coded settings.

Author: UnrealEd
Language: JAVASCRIPT
Highlight Mode: JAVASCRIPT
Last Modified: January 19th, 2011

function js_root (filename) {
	var scripts = document.documentElement.getElementsByTagName ('script');
	for (var i=0; i<scripts.length; i++)
		if (scripts[i].src && scripts[i].src.substr (scripts[i].src.length - filename.length) == filename)
			return scripts[i].src.substr (0, scripts[i].src.length - filename.length);
	return window.location.href.substr(0, window.location.href.length - window.location.pathname.length + 1)
}
 
// This is part of a small JS framework I was working on 
//(but never got around to finish it). What it does is find 
// the location of a javascript file on the server when it's 
// included via html. For example:
 
/foo/bar/myfile.js" type="application/javascript"></script>
<script type="application/javascript">
// <![CDATA[
alert(js_root('myfile.js');
// ]]>
</script>
 
// Would return http://mysite.com/js/whatever/foo/bar
 
 
There haven't been any comments added for this snippet yet. You may add one if you like.  Add a comment 
© coderzone.org | users online: 7