Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Javascript, is it possible to pass a variable into <script> "src" parameter?

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

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

I'd like twitter.js to look and see if a "handle" was passed before doing what I need it to do and returning its response back to the originating page calling twitter.js.

I had 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 is not going to work on a file that I'm calling from <script src="" />

Thanks!

like image 894
Mike B. Avatar asked Dec 20 '10 19:12

Mike B.


People also ask

Can you pass a variable to JavaScript?

Javascript pass by value:In javascript pass by value, the function is called by directly passing the value of the variable as the argument. Therefore, even changing the argument inside the function doesn't affect the variable passed from outside the function.

Are variables passed by reference in JavaScript?

It's always pass by value, but for objects the value of the variable is a reference. Because of this, when you pass an object and change its members, those changes persist outside of the function. This makes it look like pass by reference.

How do you declare a variable in script tag?

Always declare JavaScript variables with var , let , or const . The var keyword is used in all JavaScript code from 1995 to 2015. The let and const keywords were added to JavaScript in 2015. If you want your code to run in older browsers, you must use var .


1 Answers

I can see two solutions here.

First: you can process those GET parameters on the server where the twitter.js is hosted, so that it will dynamically change the js file. For example, you file is:

var handle = {{ handle }};

And your server somehow processes the file, replacing that twitter.js template file dependent on what request was sent.

The second option would be to set the global variables on the page where twitter.js is loaded, like this:

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

And in twitter.js:

var handle = window.twitter_js_handle || null;
like image 59
dmedvinsky Avatar answered Nov 02 '22 23:11

dmedvinsky