Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Javascript any way to know what host script was loaded from?

Tags:

javascript

In javascript, as a script loaded from somer host, is there any way to know what server/host I was loaded from? I need to make additional ajax requests back to that host and would prefer to figure out the host dynamically.

So if you include a javascript file on a page

<script src="http://somehost.com/js/test.js"></script>

when that javascript execute, within test.js ...

var host_loaded_from = ??? // should be somehost.com 

Thanks

like image 940
mbrevoort Avatar asked Aug 26 '10 19:08

mbrevoort


People also ask

How do you check if a script is loaded with JavaScript?

Pass the URL of JavaScript file in a <script> tag. Set the onload parameter, Trigger alert if script loaded. If not then check for loaded variable, if it is equal to false, then script not loaded.

Where script tag is placed in JavaScript?

Scripts can be placed in the <body> , or in the <head> section of an HTML page, or in both.

How are JavaScript files executed?

To execute JavaScript in a browser you have two options — either put it inside a script element anywhere inside an HTML document, or put it inside an external JavaScript file (with a . js extension) and then reference that file inside the HTML document using an empty script element with a src attribute.


2 Answers

Does the script know its own file name? ("test.js" in the OP question.)

If so, your script could query the dom for all script tags, looking for the ones with a src attribute. But you'd need to watch out for two scripts with the same file name loaded from different servers. Eg

<script src="http://somehost.com/js/test.js"></script>
<script src="http://somehost_number2.com/js/test.js"></script>

Here's JS that looks for all of the script tags in an el:

var scripts = el.getElementsByTagName('SCRIPT');
like image 136
Larry K Avatar answered Oct 24 '22 06:10

Larry K


is there any way to know what server/host I was loaded from?

Yes, it's possible except when the script is loaded asynchronously using defer or async attributes since the last script in the DOM may not necessarily be the currently executing script in that case. See the comments by @kangax for more information.

Also, this same question was posted recently.

Inside your test.js, get the last script element which will be the currently being parsed script (test.js in your case), and get its src.

// test.js
var scripts = document.getElementsByTagName('script');
var src = scripts[scripts.length - 1].src;

One the src is found, parsed the host using regex.

src.match(new RegExp('https?://[^/]*'))
["http://somehost.com"] // for your example
like image 35
Anurag Avatar answered Oct 24 '22 06:10

Anurag