Passing Variables to JavaScript Includes

1 min read

Why You Want It

Let's say a client wants to list your iphone apps on their webpage. Yes, this is 100% made up. So you give them a script tag and tell them to drop it on their site:

...
<script src="http://bendytree.com/apps.js" type="text/javascript"></script>
...

The script looks something like this:

document.write("<h1>Bendy Tree Apps</h1>");
document write("<a href='http://bendytree.com/todaysweather'>Today's Weather</a>");
document write("<a href='http://pockettap.com'>Pocket Tap</a>");

Ok lots of bad practices, blah, blah, blah, but you understand the concept. They've dropped one line of markup on their webpage and they get everything they need.

Enter the Power of Variables

What if they say, "Wellll… we really don't want to show games on our site?" (not sure where the question mark goes)

(Bad) Option 1 – Make a New Script

You could make another script called utility-apps.js which only has utilities. But that's code duplication and altogether silly.

(Bad) Option 2 – Have Them Call a Function

They could include your script and call a specific function. But this makes their markup way more messy.

...
<script src="http://bendytree.com/apps.js" type="text/javascript"></script>
<script type='text/javascript'>
    bendytree_listUtilityApps();
</script>
...

(Fantastic) Option 3 – Pass a variable to the JS include

Check this out:

...
<script src="http://bendytree.com/apps.js?utilities" type="text/javascript"></script>
...

How It Works

It's easy enough to get the url/query string of the current page, but there's no obvious way to get the url/querystring of the JavaScript file that you're executing inside of.

Queue evil laugh. Check this out:

document.write("<span style='display:none;' id='xyz'></span>");
$(function(){
    alert($("#xyz").prev().attr("src").split("?")[1]);
});

The first line writes a hidden tag with a unique id. Then, when the page loads we find that 'breadcrumb' we dropped and just grab the previous element… which is our script tag! Now just grab the "src" attribute, split it, and you've got your variable. WHAH-POW!

Leave a Reply

Your email address will not be published. Required fields are marked *