How to get the file-path of the currently executing javascript code How to get the file-path of the currently executing javascript code javascript javascript

How to get the file-path of the currently executing javascript code


Within the script:

var scripts = document.getElementsByTagName("script"),    src = scripts[scripts.length-1].src;

This works because the browser loads and executes scripts in order, so while your script is executing, the document it was included in is sure to have your script element as the last one on the page. This code of course must be 'global' to the script, so save src somewhere where you can use it later. Avoid leaking global variables by wrapping it in:

(function() { ... })();


All browsers except Internet Explorer (any version) have document.currentScript, which always works always (no matter how the file was included (async, bookmarklet etc)).

If you want to know the full URL of the JS file you're in right now:

var script = document.currentScript;var fullUrl = script.src;

Tadaa.


The accepted answer here does not work if you have inline scripts in your document. To avoid this you can use the following to only target <script> tags with a [src] attribute.

/** * Current Script Path * * Get the dir path to the currently executing script file * which is always the last one in the scripts array with * an [src] attr */var currentScriptPath = function () {    var scripts = document.querySelectorAll( 'script[src]' );    var currentScript = scripts[ scripts.length - 1 ].src;    var currentScriptChunks = currentScript.split( '/' );    var currentScriptFile = currentScriptChunks[ currentScriptChunks.length - 1 ];    return currentScript.replace( currentScriptFile, '' );}

This effectively captures the last external .js file, solving some issues I encountered with inline JS templates.