markzzz
markzzz

Reputation: 48035

How can I get the src of the current loaded script?

I load a script from a website:

<script type='text/javascript' src='http://www.mybridge.com/scripts/init.js?IDL=1'></script>

Inside this init.js script being loaded I have:

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

but if I try to watch at the src:

console.log("src is: "+myScript.src);

it shows to me a link of another script, not the src of the current (loaded/processed) script.

Where am I wrong? How can I do it?

Upvotes: 0

Views: 66

Answers (2)

Riad
Riad

Reputation: 3870

You can try this also:

var scripts = document.getElementsByTagName('script');
console.log(scripts);
var len = scripts.length;
for(var i = 0 ; i < len ; i++){
    if(scripts[i].src.search('init') >= 0){
       console.log(scripts[i].src) ;
    }
}

JSFIDDLE Demo

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382464

To get the URL of the script, you have to know a little more about your scripts, as there's no reason the script you want is the last one in the HTML document.

For example, if you know its name is "init.js" and you want the IDL parameter, you may do

function getIDL(){
     var scripts = document.getElementsByTagName('script');
     for (var i=0; i<scripts.length; i++) {
         var m = scripts[i].src.match(/\/init\.js\?IDL=(\d+)/);
         if (m) {
            return m[1]; // return the IDL
         }
     }
     return null;
}

Upvotes: 1

Related Questions