views:

122

answers:

4

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

<script type="text/javascript" src="http://www.example.com/script.js?key=value"&gt;&lt;/script&gt;
A: 

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

Brian Agnew
+2  A: 

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&gt;&lt;/script&gt;

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)

SLaks
Yes, but perhaps defined in a namespace other than the global.
Upper Stage
That would be a good idea.
SLaks
the scriptaculous example proves that you can do this just fine, without assigning variables.
Derek P.
I know that this is possible, but it's not that simple to do.
SLaks
+6  A: 

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"
CMS
That's very interesting.
Emanuil
A: 

to add to SLaks answer, json encoding the data handles your escaping needs. in php: json_encode()

fsb