Find your own origin in JavaScript

Is there any way to find the source of the current script run? I would like to add a different behavior depending on where the script was loaded.

eg. was downloaded from:

http://localhost:8080/js/myscript.js 

vs

 http://www.myhost.com/js/myscript.js 

I'm not the one who downloads, so I cannot add some information at boot time, and the script is loaded dynamically with $.getScript() , so I cannot search for the item.

+4
source share
3 answers

When a script is called, if it is not marked as defer or async , it will always be the last element on the page at that point in time (since it blocks).

Using this, you can do the following:

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

Then do as you wish.

+5
source

Well .., this is a kind of hack ..!

First you need to get all script elements

 var all_scripts = document.getElementsByTagName('script'); 

select current script

 var current_script = scripts[all_scripts.length-1]; 

Now you can see the src script

 alert(current_script.src); 
+1
source

UPDATED changed removed var o = $(this) as suggested by @FelixKling

UPDATED EXAMPLE

 $.getScript("http://localhost:8080/js/myscript.js") .done(function(data, textStatus, jqxhr) { // this.url is the script url passed to $.getScript if(this.url.search('http://localhost:8080') != -1){ alert("do one thing for http://localhost:8080/js/myscript.js"); } if(this.url.search('http://www.myhost.com') != -1){ alert("do another thing for http://www.myhost.com/js/myscript.js"); } }) .fail(function(){ alert("somethign went wrong"); }); 

JsFiddle example

-3
source

Source: https://habr.com/ru/post/1497227/


All Articles