Friday, April 23, 2010

Get Parameters from your Script Tag

I had a situation where I only needed to pass one variable to a script and asking users to do something like this seemed cumbersome
<script type="text/javascript">
var color = blue;
<script type="text/javascript" src="test.js"></script>
I think it'd be better to have them include the variable setting in the script URL. Something like this:
<script type="text/javascript" src="test.js?color=blue"></script>
Of course, after I figured it all out, I found it posted elsewhere on the internet, but the other method uses javascript and I figured out a nice jQuery method :P

So this method uses a compressed version of the function from an older post "Extracting URL parameters with Javascript". Here is the setup:
<script type="text/javascript" src="test.js?color=blue&background=#222"></script>
Access the script, as above, by adding the parameter to the end of the script url, preceded by a question mark, an equal sign between the key and value, then followed by an ampersand for any additional parameters:


In the script you load, add the following:
var scriptSrc = $('script[src*=test.js]').attr('src');
var color = gup( 'color', scriptSrc );
var background = gup( 'background', scriptSrc );

// do something with the parameters
alert( 'color = ' + color + ', background = ' + background );

// extract out the parameters
function gup(n,s){
n = n.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");
var p = (new RegExp("[\\?&]"+n+"=([^&#]*)")).exec(s);
return (p===null) ? "" : p[1];
  • First off, this method requires that you have jQuery loaded on your page before you load this script.
  • In the first line, make sure the "test.js" matches the name of the javascript file you are loading. This code should be inside this file as well, but even this isn't necessary - you can grab parameters from other script tags.
  • Add a line for each parameter in the script src. The parameter key must match in both places.
    var color = gup( 'color', scriptSrc );
  • If a parameter doesn't exist in the script src, then the result of the gup() function will be an empty string.