Tuesday, November 24, 2009

Using URL parameters in Javascript

This is a simple function to parse parameters out of a URL and return them as properties of an object:

<script type="text/javascript">
// example URL: http://example.com/script.html?foo=hello+world&bar=goodbye

// function to parse the URL
function getParams (url) {

// split url into host/path and args, then split args into an array
var argstr = url.split("?")[1] || '';
var args = argstr.split("&");

var params = new Object;

// args will have len=1 even if split() returned empty, so fix that
var length = args[0] ? args.length : 0;

// loop args and load into object properties
for ( var i=0; i<length; i++ ) {
var p = args[i].split("=");
params[p[0]] = unescape(p[1]).replace(/\+/g, ' ');
}

return(params);
}

// send it our URL
var params = getParams(window.location.href);

// use the parameters
document.write("foo = " + params.foo + "<br>");
document.write("bar = " + params.bar + "<br>");

// output is:
// foo = hello world
// bar = goodbye
</script>

Loading Javascript libraries on demand

I needed to load the Google visualization API, but only needed it under certain conditions. Not wanting the overhead if not needed, I looked around for a way for Javascript to include external libraries. Sadly, it appears this facility is lacking, so I came up with the following hack.

// create the script element with no src set
<script language="Javascript" type="text/javascript" id="google_jsapi"></script>
...
// add the src to the script element
if ( some_condition ) {
document.getElementById('google_jsapi').src = 'http://www.google.com/jsapi';
}
...
// use the library
window.onload = do_stuff();