Get query string variables of Javascript files

Looking at different scripts linking to Javascript and AJAX frameworks such as Scriptaculous, I noticed that it allows loading of particular parts of it by adding them in the following query string such as this:

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

Looking at scriptaculous.js itself, it relied on some built-in functionality for that. I was unsuccessful in finding online a ready function to do exactly that, so inspired by this piece of code and borrowing the regex part of it, I wrote a function which grabs the additional parameters and allows using them in the Javascript:

function getJSvars(script_name, var_name, if_empty) {

var script_elements = document.getElementsByTagName(‘script’);

if(if_empty == null) {
var if_empty = ;
}

for (a = 0; a < script_elements.length; a++) {
   var source_string = script_elements[a].src;
       if(source_string.indexOf(script_name)>=0) {

       var_name = var_name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
       var regex_string = new RegExp("[\\?&]"+var_name+"=([^&#]*)");
       var parsed_vars = regex_string.exec(source_string);
       if(parsed_vars == null) { return if_empty; }
       else { return parsed_vars[1]; }

      }
   }
}

Usage of it is simple: if you have a Javascript which should parse some dynamic variables (such as user or account ID), you can include it right after the included Javascript like this:

<script type="text/javascript" src="script.js?var1=value1&var2=value2"></script>

instead of creating a server-side generated dynamic Javascript using PHP or other language. The values of variables like var1 can be retrieved like this:

var var1 = getJSvars(‘script.js’, ‘var1′);

You can also add a value as third parameter to output in case var1 is empty, but it is optional.

1 Comment so far

  1. Adrian on September 9th, 2009

    Thank you very much for this piece of code.
    Was looking everywhere and this works a treat.

Leave a Reply