BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News AJAX developers continue migrating to unobtrusive JavaScript

AJAX developers continue migrating to unobtrusive JavaScript

This item in japanese

Unobtrusive JavaScript is an emerging technique that separates JavaScript from HTML markup. This is quite similar to the separation between styling and HTML that came about with the creation of CSS in the late 90s. For example, obtrusive JavaScript would add an onClick handler directly to an input field like this:
<input id="field" onclick="alert('hello')" />
Unobsutrive JavaScript waits until the page has finished loading before hooking up the event handler to the input field:
<script type="text/javascript">
Event.observe(window, 'load', function() {
Event.observe($('field'), 'click', function() {
alert('hello');
};
});
</script>

<input id="field" />

This keeps the HTML (our input tag in this example) clean and provides the developer with a single point of reference for debugging JavaScript code. Unobtrusive JavaScript is typically stored in external .js files as opposed to being embedded inside <script> tags in the HTML page itself. While the unobtrusive example here takes up more lines of code, larger blocks of JavaScript will generally end up being clearer and more concise when made unobtrusive.

Some other benefits of unobtrusive JavaScript include:

  • Separation of concerns: the behavior layer is separated from the content and presentation layers
  • Easier handling of browser inconsistencies
  • Concise code that's easier to read

When used with open source libraries like Prototype, unobtrusive JavaScript gets even easier to create. There are even frameworks specifically designed for taking obtrusive JavaScript and making it unobtrusive.

Low Pro, for example, adds several useful helper functions to Prototype, dramatically improves access to the browser's event model, and provides a behavior library that makes it a breeze to hook up unobtrusive triggers. Our previous example can be written in Low Pro like this:

<script type="text/javascript">
Event.addBehavior({
'input#field:click' : function(e) {
alert('hello');
}
});
</script>

<input id="field" />

Behaviors are automatically hooked up after the page finishes loading. Additional behaviors can be added using CSS selectors to pick elements for triggering.

With the number of AJAX-enabled web sites steadily increasing, JavaScript is becoming a much larger part of web application development. Keeping JavaScript unobtrusive makes it much simpler to develop flashy features. It will also make future maintenance of these web sites much easier and more cost effective.

Rate this Article

Adoption
Style

BT