Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the uri of the .js file itself

Tags:

javascript

is there a method in JavaScript by which I can find out the path/uri of the executing script.

For example:

  1. index.html includes a JavaScript file stuff.js and since stuff.js file depends on ./commons.js, it wants to include it too in the page. Problem is that stuff.js only knows the relative path of ./commons.js from itself and has no clue of full url/path.

  2. index.html includes stuff.js file as <script src="http://example.net/js/stuff.js?key=value" /> and stuff.js file wants to read the value of key. How to?

UPDATE: Is there any standard method to do this? Even in draft status? (Which I can figure out by answers, that answer is "no". Thanks to all for answering).

like image 975
Vikrant Chaudhary Avatar asked Jan 22 '23 23:01

Vikrant Chaudhary


1 Answers

This should give you the full path to the current script (might not work if loaded on request etc.)

var scripts = document.getElementsByTagName("script");
var thisScript = scripts[scripts.length-1];
var thisScriptsSrc = thisScript.src;
like image 84
Sean Kinsey Avatar answered Feb 02 '23 06:02

Sean Kinsey