One of the things we needed to tackle recently, was dropping content onto our 3rd party vendor sites. We’ve been doing this with JavaScript/JSON applications. To keep things simple, we needed a way to parameterize the JavaScript. We could do this with a bunch of JS variables before calling the external JS file, but that seemed…inelegant.
<script>
var mode = "full";
var brand = "Acme";
var autorun = false;
</script>
<script src="somefile.js"></script>
In my PHP days, we could handle this with a simple query string in the URL: somefile.php?mode=full&brand=Acme&autorun=false
But why can’t we do this with the SRC attribute in the script tag? Well, jsParam allows just that to happen.
<script src="somefile.js?mode=full&brand=Acme&autorun=false"></script>
The function is still a work in progress, but it currently compensates for the fact that all the params are being passed as strings. It looks for numbers and booleans and converts them over. I also included the ability to log the params to the console so you can test to see if they’re working correctly.
/*
Copyright 2013 by Brian Rollins.
For the latest version, checkout https://github.com/BrianRollins/jsParam
Questions/Comments: me at brianrollins.com
*/
/**
Function jsParam
Params:
sourceID: (String) ID of the script tag you want examined for parameters. Do not use # before the ID.
logParams: (Boolean | Optional) Sends a log of the parameters and their types to the console.
Returns: Array (or null if no params are found);
*/
var jsParam = function(sourceID, logParams) {
if (typeof logParams === 'undefined') {
logParams = false;
}
var params = [];
var parts = document.getElementById(sourceID).src.split('?');
if (typeof parts[1] !== 'undefined') {
parts = parts[1].split('&');
for(i=0; i<parts.length; i++) {
var t = parts[i].split('=');
//Because everything comes in as a string, we're going to do some cleanup for Booleans and Numbers.
//Fix booleans
if (t[1] === "true") {
t[1] = true;
} else if (t[1] === "false") {
t[1] = false;
}
//Fix numbers
else if (t[1] == parseFloat(t[1])) {
t[1] = parseFloat(t[1]);
}
params[decodeURIComponent(t[0])] = decodeURIComponent(t[1]); //Decode that ugly URI stuff.
}
if(logParams) {
console.log('*** jsParam ('+sourceID+') ***');
for(strName in params) {
var c = params[strName];
console.log(strName + " : " + c + " (" + typeof c + ")");
}
}
return params; //Array of params.
} else {
//No Params found.
return null;
}
};