0

I have created a <script> tag in an http://example.com/index.html tag using javascript like

 (function() {
            var script_tag = document.createElement('script');
            script_tag.setAttribute("type","text/javascript");
            script_tag.setAttribute("src", "http://example2.com/xyz/def/internal.js");
            (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
    })();

Now inside this internal.js file i want to get its file path "http://example2.com/xyz/def/"

void
  • 36,090
  • 8
  • 62
  • 107
  • You don't need to use `.setAttribute()` to set those properties, and you don't need to set the "type" property at all. Just `script_tag.src = "...";` will work. – Pointy Jan 30 '15 at 14:22
  • @pointy Okay, btw it was not what i asked. Thanks anyway. – void Jan 30 '15 at 14:24
  • @A1rPun No, here the script is created via js itself, so it may not probably be the last script created. – void Jan 30 '15 at 14:25
  • @void it will be the last ` – Pointy Jan 30 '15 at 14:29
  • No the current script will be the script tag itself not the js file. – void Jan 30 '15 at 14:37
  • Yes. Thats where I am stuck. – void Jan 30 '15 at 14:38
  • There are other possibilities in some of the more recent answers in the linked question. If all else fails, you can always just put the script path in a global variable, since the code that *loads* it certainly knows the URL. – Pointy Jan 30 '15 at 14:46

1 Answers1

1

Inside internal.js

var scripts = document.getElementsByTagName('script'),
    script = scripts[scripts.length - 1], url = "";
if (script.getAttribute.length !== undefined) {
   url = script.src;
}
else
{
   url = script.getAttribute('src', -1);
}

With modern browsers this should work

url = document.currentScript.src;
chridam
  • 100,957
  • 23
  • 236
  • 235
  • It wont work, because scripts[scripts.length - 1] will return the – void Jan 30 '15 at 14:37