get js file query param from inside it

Posted by vsync on Stack Overflow See other posts from Stack Overflow or by vsync
Published on 2009-12-31T14:16:31Z Indexed on 2010/05/04 12:58 UTC
Read the original article Hit count: 178

Filed under:

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.getAttribute('src', 2);

   return getQueryParams('userId',s);
};

© Stack Overflow or respective owner

Related posts about JavaScript