JavaScript - How do I get the URL of script being called?

From http://feather.elektrum.org/book/src.html:

var scripts = document.getElementsByTagName('script');
var index = scripts.length - 1;
var myScript = scripts[index];

The variable myScript now has the script dom element. You can get the src url by using myScript.src.

Note that this needs to execute as part of the initial evaluation of the script. If you want to not pollute the Javascript namespace you can do something like:

var getScriptURL = (function() {
    var scripts = document.getElementsByTagName('script');
    var index = scripts.length - 1;
    var myScript = scripts[index];
    return function() { return myScript.src; };
})();

You can add id attribute to your script tag (even if it is inside a head tag):

<script id="myscripttag" src="http://site2.com/myscript.js"></script>

and then access to its src as follows:

document.getElementById("myscripttag").src

of course id value should be the same for every document that includes your script, but I don't think it is a big inconvenience for you.


Everything except IE supports

document.currentScript

Simple and straightforward solution that work very well :

If it not IE you can use document.currentScript
For IE you can do document.querySelector('script[src*="myscript.js"]')
so :

function getScriptURL(){
 var script =  document.currentScript || document.querySelector('script[src*="myscript.js"]')
 return script.src
}
update

In a module script, you can use:

 import.meta.url

as describe in mdn