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):

<scripttype="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:

functiongetScriptVariable(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 = newRegExp("[\\?&]"+key+"=([^&#]*)");
      var keyValues = r.exec(scriptSource);
      return keyValues[1];
    }
  }
}

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

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

And use the above function in this way:

varvalue = 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:

<scripttype="text/javascript">var key = value;
</script><scripttype="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:

<scripttype="text/javascript">varMyScriptParameters = {
        param1: 123,
        param2: "Hello",
        param3: newDate,
        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"