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:
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:
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:
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:
You can also add a value as third parameter to output in case var1 is empty, but it is optional.
Comments(1)
Thank you very much for this piece of code.
Was looking everywhere and this works a treat.