In Javascript can I pass a variable to the <script> "src" parameter?

Is it possible in Javascript to pass a variable through the src parameter? i.e.

 <script type="text/javascript" src="http://domain.com/twitter.js?handle=aplusk" />` 

I would like to see twitter.js see if the descriptor was passed before doing what I need and return its response to the original page that calls twitter.js .

I originally created a function in twitter.js that did the following:

 function getHandle() { var vars = [], hash, username; var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); for(var i = 0; i < hashes.length; i++) { hash = hashes[i].split('='); if (hash[0] == 'handle') username = hash[1]; } return username; } 

The problem, and it makes sense, is that window.location.href will not work on the file that I call from <script src="" />

Thanks!

+4
source share
3 answers

Here I see two solutions.

First: you can process these GET parameters on the server hosting twitter.js so that it dynamically changes the js file. For example, the file:

 var handle = {{ handle }}; 

And your server is somehow processing the file, replacing this twitter.js template file depending on what request was sent.

The second option is to set global variables on the page where the .js twitter is loaded, for example:

 <script type="text/javascript"> window.twitter_js_handle = 'aplusk'; </script> <script type="text/javascript" src="http://domain.com/twitter.js" /> 

And on twitter.js:

 var handle = window.twitter_js_handle || null; 
+7
source

I use the following template to convert query variables from <script src="script.js?foo=bar&baz=zing"></script> into object pairs: key-key: value. The code is at the top of the script.js:

 var getVars = {}; (function(){ var scripts, currentScript, queryString; scripts = document.getElementsByTagName('script'); currentScript = scripts[ scripts.length - 1 ]; queryString = currentScript.getAttribute('src').replace(/[^\?]*/,'').split('&'); for(var i=0;i<queryString.length;i++){ var keVal = queryString[i].split('='); getVars[ keyVal[0] ] = keyVal[1]; } }()); // console.info( getVars ); // Object { foo="bar", baz="zing"} 

This probably won't work with deferred / asynchronously added script elements, as it relies on immediate code execution.

+6
source

Sure. The only way to access this parameter is through the server side. So, make twitter.js a PHP page (using mod_rewrite or something else) that grabs $_GET['handle'] and then serves as Content-Type: text/javascript and just dumps the contents of js.

+1
source

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


All Articles