Using Xml and jQuery to configure your unobtrusive client side scripts.

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:

<!-- wp:paragraph --> <p>Script.js:</p> <!-- /wp:paragraph --> <!-- wp:preformatted --> <pre class="wp-block-preformatted">(function($) {<br><br>&nbsp; var serviceUrl = window.ScriptConfig.serviceUrl;<br>&nbsp; // Where ScriptConfig is declared on your target page.<br><br>})(window.jQuery);</pre> <!-- /wp:preformatted -->
Code language: HTML, XML (xml)


<script type="text/javascript"> window.ScriptConfig = { serviceUrl: "/path/to/service" }; </script> <script type="text/javascript" src="/script.js"></script>
Code language: HTML, XML (xml)

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>
Code language: HTML, XML (xml)

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);
Code language: JavaScript (javascript)

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

Leave a Reply

Your email address will not be published.

Related Post