Passing parameters to JavaScript files

Aug 21

Written by: Joe Brinkman
8/21/2008 11:07 AM  RssIcon


There appears to me to be a recurring pattern I see on many web sites.  Often you will have a JavaScript library that you want to use which requires certain variables be defined in your web page.  I have seen this pattern repeated for many different widgets that you may want to include on your page.  [more]The pattern generally looks like this:

While this works, I didn’t like the need to create the extra script block just to set a few values.  There are some cases where the second script block is needed because you need to calculate the value, but often the values are fairly static or are calculated on the server when the page is generated.  In these cases, the extra script block should not be needed.  What I really wanted was a way to compress this down to a single script block.


Everyone I talked to suggested that I create a filehandler that runs on the server side which would accept parameters and then output the JavaScript file with the parameters embedded.  This just seemed like it was too much work for a problem that seems so simple.

After thinking through the problem a bit, I decided that the best approach was to just use a regular expression to find the parameters which could then be easily parsed.  In order to find the appropriate parameters, I need to add an id attribute to the script block so I could use getElementById to find the correct script block.  So given the following script block:


I can use some simple JavaScript to get the src attribute:

var scriptSrc = document.getElementById("myscript").src.toLowerCase();

In searching around the Internet, I found that Hendrik Swanepoel had already provided code for easily parsing a querystring.  In reading through the blog, I found that Colin actually provided a better solution in the comments.  This was exactly what I wanted.  Now I had all the parts for a complete solution:

function QSObject(querystring){ 
    //Create regular expression object to retrieve the qs part 
    var qsReg = new RegExp("[?][^#]*","i"); 
    hRef = unescape(querystring); 
    var qsMatch = hRef.match(qsReg); 
    //removes the question mark from the url 
    qsMatch = new String(qsMatch); 
    qsMatch = qsMatch.substr(1, qsMatch.length -1); 
    //split it up 
    var rootArr = qsMatch.split("&"); 
        var tempArr = rootArr[i].split("="); 
        if(tempArr.length ==2){ 
            tempArr[0] = unescape(tempArr[0]); 
            tempArr[1] = unescape(tempArr[1]); 
            this[tempArr[0]]= tempArr[1]; 
var scriptSrc = document.getElementById("myscript").src.toLowerCase();
qs = new QSObject(scriptSrc); 
document.write("obj1=" + qs.obj1 + "
document.write("obj2=" + qs.obj2 + "

Maybe someone else has a better solution, but this seemed to work for my purposes.

4 comment(s) so far...


re: Passing parameters to JavaScript files

Not sure if this would fit, but I use a server side component to generate client script vars for me. I simply add properties to a scriptvars component and it dumps out the appropriate java script in the form of an object (ie. one reference). This still ends up costing a script block, but it makes for a nice clean generic model so I can just say (for example: scriptVars.myServerVar) and it just works anywhere. The component can also optionally write the values back to the server if configured to do an auto-postback. This can be useful for Ajax apps that want to update vars and then have the updated values available at Postback as well.

By Rick Strahl on   8/21/2008 6:37 PM

re: Passing parameters to JavaScript files

@Rick - The problem that prompted this post was that I needed a simple script that people could drop on their site for displaying a conference badge. I really wanted to keep the invocation tight without opening up another endpoint on the server. My final script block looks like this which is really simple for exhibitors wanting to post this on their site: [Ignore the elipses to get past BlogEngine filters]

By Joe Brinkman on   8/21/2008 7:56 PM

re: Passing parameters to JavaScript files

This is fine in all situations other than documents using HTML 4.01 Strict or XHTML. In this case the document will technically no longer be valid because the "ID" attribute is not supported for the Script element and ampersands need to be replaced with an entity reference in the value of the "src" attribute. I think for your use case it's probably not a big deal, but if you are interested, the workaround is fairly simple: For the ID, use document.getElementsByTagName("script") and use the last element of the array (which is the script element for the executing script). For the ampersand, either use the entity reference or a different separator. If you use the latter approach, then for semantic validity you may also want to change the "?" to "#" since it would no longer be a standard querystring. I posted the complete code for this approach here:

By Nik Kalyani on   8/22/2008 5:35 PM

re: Passing parameters to JavaScript files

@Nik - Thanks for the update. I did check on the ID attribute before using it, but foolishly relied on various HTML sites which indicated ID attribute was supported. I should have known better and went straight to the spec.

By Joe Brinkman on   8/25/2008 6:09 AM