How can I obtain the hostname or address of my .js script from inside the .js script?
I have a web site which downloads the same script from any number of different servers:
<script type="text/javascript" src="http://server1.example.com/hello.js"></script>
<script type="text/javascript" src="http://server2.example.com/hello.js"></script>
<script type="text/javascript" src="http://server3.example.com/hello.js"></script>
<script type="text/javascript" src="http://server4.example.com/hello.js"></script>
Each script has a locally-scoped vari开发者_JS百科able which has to be the hostname of the server that script was downloaded from: so when I download the script from server1.example.com
that variable's value has to be server1.example.com
.
Can this be done with absolutely no server-side programming? (AJAX requests can be sent, but the solution cannot include any server-side code)
Please note that I am looking for the host which the script is hosted on, not the host of the current browser page; that means I am not looking for window.location
.
I think the below code can help:
var scripts = document.getElementsByTagName('script');
for(var a = 0; a < scripts.length; a++){
if(scripts[a].src.indexOf('<<<--###-->>>') > 0 )
var ThisScriptPath = scripts[a].src.substr( 0, scripts[a].src.lastIndexOf('/'));
}
You will need to replace the <<<--###-->>> with your script's name, and you will have the path stored in ThisScriptPath (remember to use the final slash)
Tip: Use an alert to check the results before getting into production
You can extract from window.location.host the first part of the domain name with regex.
You can use that in order to extract the first part
var host = window.location.host;
host = host.match(/^[\d\w]+/);
精彩评论