Get the path of executed Javascript file

Written by pelister. Posted in Jquery

I spent a lot of time searching for jQuery code snippet that could fetch the current url path from where the jQuery file is executed. But jQuery method

$(location).attr('protocol') + "//" + $(location).attr('host');

fetches the url of the current page. But to fetch the url of the path from where the Javascript is executed, is not possible with pure jQuery method unless you use some jQuery plugin or write your own function. Let us take an example, my Javascript file is executed from here – http://somedomain/folder/script.js, but when I use the above jQuery method the url returned will be http://somedomain. But I need the url path http://somedomain/folder, the actual location from where the jQuery or Javascript is executed.

In case of php it is lot easier to get the current directory from where the php script is executed. Also jQuery is executed at the client side, that is in the browser window, so no way to get the path of the Javascript file from the server. So I wrote my own function with jQuery, here it is.

function urlofdoc ( jsfile ) {

	var scriptElements = document.getElementsByTagName('script');
	var i, element, myfile;

		for( i = 0; element = scriptElements[i]; i++ ) {

			myfile = element.src;

			if( myfile.indexOf( jsfile ) >= 0 ) {
				var myurl = myfile.substring( 0, myfile.indexOf( jsfile ) );

			}
		}
	return myurl;
}

A bit of explanation – Our function urlofdoc ( jsfile ) takes the file name as argument, so lets us call the function like this

var myurl = urlofdoc ( "script.js" );

getElementsByTagName will fetch all the script tags and store it in an array, which will contain the whole string from opening script tag to close tag

script path in jquery

after that every element source is checked for the occurrence of our file.

if( myfile.indexOf( jsfile ) >= 0 ) {
		var myurl = myfile.substring( 0, myfile.indexOf( jsfile ) );

}

if the file is found, then we trim the filename using substring from the full url and return the path, in our example if we call the urlofdoc function with script.js as argument, it  will return http://somedomain/folder.

1 Star2 Stars3 Stars4 Stars5 Stars (4 votes, average: 5.00 out of 5)
Loading...
pelister
3D modeler and Web designer. Founder of Techlister. Love to build sites using WordPress and Joomla. Interested in Astronomy, project member of SETI (Search for Extra Terrestrial Intelligence).

Tags: , , , ,

Comments (1)

  • James Bayley

    |

    Thank you for publishing this post. It saved me a lot of time.

    Reply

Leave a comment

Techlister© - 2012