Part of my day job is to maintain an online purchase path, and through my recent efforts to refactor and streamline the code, I’ve come across a technique that better enables me to build my scripts in such a way that they are truly unobstrusive. But what do I mean by all this? Ok, say you have some code such as:

Script.js:

(function($) {

  var serviceUrl = window.ScriptConfig.serviceUrl;
  // Where ScriptConfig is declared on your target page.

})(window.jQuery);

Page.html:

<script type="text/javascript">
  window.ScriptConfig = {
    serviceUrl: "/path/to/service"
  };
</script>
<script type="text/javascript" src="/script.js"></script>

The problem with the above scenario, is that the ordering of scripts to config is really important, otherwise you’re attempting to use values in your script which are still potentially undefined. Also, if you’re trying to achieve a semantically clean page (where the page’s responsibility is to represent data, no presentation, not logic) – this kinda violates that.

What you can do though, is instead of relying on your scripts to be javascript, lets set them to “text/xml”:

<script id="scriptConfig" type="text/xml">
  <config serviceUrl="/path/to/service" />
</script>

Essentially, by using xml in your script tags, you can then take advantage of your browsers xml parser to read the document in and configure your scripts. Let’s change our script:

(function($) {
  
  var serviceUrl;
  
  $(function() {
    var xml = $.parseXML($("#scriptConfig").html());
    
    serviceUrl = $(xml).find("config").attr("serviceUrl");
  });

})(window.jQuery);

Now, in our script file, we can use jQuery’s parseXML function to build an Xml DOM. Because this is a DOM object, we can then use jQuery itself to interrogate the model to find elements, attributes.

Note: You have to use “html()”, and not “text()” as the latter does not work in IE.

This also allows us to have a completely script free page :-)

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)