Skip to content Skip to sidebar Skip to footer

Passing Key-value Pairs To A JavaScript File

Can you pass key-value pairs to a JavaScript file like that:

Solution 1:

That technique is used by scriptaculous (see line 54):

<script type="text/javascript" src="scriptaculous.js?load=effects,dragdrop">
</script>

You can achieve this by inspecting the source of the script elements on your page, I leave you a framework independent function:

function getScriptVariable(scriptName, key) {
  var scripts = document.getElementsByTagName('script'),
      n = scripts.length, scriptSource, i, r;

  for (i = 0; i < n; i++) {
    scriptSource = scripts[i].src;
    if(scriptSource.indexOf(scriptName)>=0) {
      r = new RegExp("[\\?&]"+key+"=([^&#]*)");
      var keyValues = r.exec(scriptSource);
      return keyValues[1];
    }
  }
}

Then you can embed a script in the way you want:

<script type="text/javascript" src="myScript.js?myKey=myValue">
</script>

And use the above function in this way:

var value = getScriptVariable('myScript.js', 'myKey'); // "myValue"

Solution 2:

Not easily, unless you want them to be processed by server-side code that generates Javascript.

However, you can define variables in an earlier script block as parameters.

For example:

<script type="text/javascript">
    var key = value;
</script>

<script type="text/javascript" src="http://www.example.com/script.js></script>

You can then use the key variable in script.js just like any other variable.

EDIT: As Upper Stage pointed out, it would be a better idea to put the parameters inside their own namespace.

For example:

<script type="text/javascript">
    var MyScriptParameters = {
        param1: 123,
        param2: "Hello",
        param3: new Date,
        param4: function(text) { ... }
    };
</script>

You could then write MyScriptParameters.param2 in script.js (Or in any other script on the page)


Solution 3:

Not like that. The above will perform a GET request on the HTTP server with parameters key=value. Those won't (normally) impact on the resource script.js being returned to you (which is what the above is asking for).


Post a Comment for "Passing Key-value Pairs To A JavaScript File"