get js file query param from inside it
I load this file with some query param like this:
src='somefile.js?userId=123'
I wrote the below function in 'somefile.js' file that reads the 'userId' query param
but I feel this is not the best approach. Frankly, its quite ugly. Is there a better way?function getId(){
var scripts = document.getElementsByTagName('script'), script;
for(var i in scripts){
if( scripts.hasOwnProperty(i) && scripts[i].src.indexOf('somefile.js') != -1 )
var script = scripts[i];
}
var s = (script.getAttribute.length !== undefined) ?
script.getAttribute('src') :
script.g开发者_如何学运维etAttribute('src', 2);
return getQueryParams('userId',s);
};
// extracts the params from the currently running (external) script
var getScriptQp = (function(){
var scripts = document.getElementsByTagName('script');
var this_script_tag = scripts[scripts.length - 1]; //script tag of this file
if( typeof this_script_tag != undefined && this_script_tag.src )
var s = this_script_tag.src;
else{
return this.customer;
}
return s;
})();
// gets the Query Params of a givver query string
function getQueryParam(name, query){
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(query);
if (results == null)
return "";
else
return results[1];
}
getQueryParam( 'param',getScriptQp );
Reading the script
elements in the head
section is the way to go. There's an article with sample code. This approach seems fragile as the name of the script is hardcoded and if it is renamed it might break.
Alternative ways are:
- Just set a JS variable with that value. E.g.
<script>var userId = 123;</script>
. - Put the value in a hidden (input) element somewhere in the HTML DOM and access it the usual way.
That said, keep in mind that JS code runs at the client side and is fully controllable by the client. You should for instance really not let the JS do some user-specific logic which is dependent on the userId. In such case, rather keep the userId in session in the server side and make use of ajax to get the result.
Someone correct me if I'm wrong, but I'm pretty sure that if you pass your params via the URL to your script it essentially means that the client will never cache your JS file, since everytime it appears as a different URL and will be re-downloaded.
精彩评论