Unobtrusive JavaScript

From Seo Wiki - Search Engine Optimization and Programming Languages

Jump to: navigation, search

"Unobtrusive JavaScript" is an emerging technique in the JavaScript programming language, as used on the World Wide Web. Though the term is not formally defined, its basic principles are generally understood to include:


The need for a new paradigm

JavaScript historically has had a reputation as a clumsy, hackish language unsuitable for serious application development[3], [4]. This has been largely due to inconsistent implementations of the language itself and the Document Object Model[5] in various browsers, and the widespread use of buggy cut-and-paste code. Runtime errors were so common (and so difficult to debug) that few programmers even tried to fix them, as long as the script behaved more or less the way it was supposed to[6]; scripts often failed completely in some browsers.

The recent emergence of standardized browsers, JavaScript frameworks and high-quality debugging tools have made organized, scalable JavaScript code possible, and the emergence of AJAX interfaces has made it essential.

Whereas JavaScript was once reserved for relatively simple and non-critical tasks such as form validation and decorative novelties, it is now being used to write large, complex codebases that are often part of a site's core functionality. Run time errors and unpredictable behavior are no longer minor annoyances; they are fatal flaws.

Advocates of Unobtrusive JavaScript see it as part of the larger Web standards movement; much as the demand for cross-browser compatibility has driven the increasing emphasis on standardized markup and style, the increasing demand for rich Internet applications is driving the movement toward better practices with the use of JavaScript. The term was invented in 2002 by Stuart Langridge,[7]. In that article he argues for a way to keep all JavaScript code, including event handlers, outside of the HTML. Stuart Langridge has since expanded upon this thought in book [8] and article format.[9]

Separation of behavior from markup

Traditionally, JavaScript often was placed inline together with an HTML document's markup. For example, the following is a typical implementation of JavaScript form validation when written inline:

<input type="text" name="date" onchange="validateDate" />

Adherents to "Unobtrusive Javascript" argue that the purpose of markup is to describe a document's structure, not its programmatic behavior and that combining the two negatively impacts a site's maintainability for similar reasons that combining content and presentation does. They also argue that inline event handlers are harder to use and maintain, when one needs to set several events on a single element or when one is using event delegation. Nor can they be used with custom events.

The unobtrusive solution is to register the necessary event handlers programmatically, rather than inline. That is to say, rather than using the event handlers as shown with the hyperlink above to directly fire the desired action, the following methods are used. These are commonly achieved by assigning a particular CSS selector to all elements which need to be acted upon by the script:

<input type="text" name="date" />

The script can then look for all input elements with the name date, and set them up accordingly:

Using native JavaScript, HTML5 events and DOM Level 2 event listeners:

document.addEventListener("domcontentloaded", function() {
    // domcontentloaded will fire when the DOM is loaded but unlike "load" it does not wait for images, etc.
    // It is being standardized in HTML5
    // It is assumed that there is only one element with name="date"
    document.getElementsByName("date")[0].addEventListener("change", validateDate, false);
}, false);
function validateDate(){
	// Do something when the content of the 'input' element with the name 'date' is changed.

The above example will not work in all browsers, particularly Internet Explorer, including version 8, do not support DOM 2 event listeners. In practice developers often use libraries to get away from browser inconsistencies and deficiencies. The following script is specific to the MooTools JavaScript library, but accomplishes the same setup:

window.addEvent('domready', function() {
	$$('input[name=date]').addEvent('change', validateDate);

The following script is specific to the jQuery JavaScript library:

	$('input[name=date]').bind('change', validateDate);

Because the intended purpose of the name attribute is to describe the semantic role of an element, this approach is consistent with modern standards-based markup practices.

Best practices

Though the essence of unobtrusive JavaScript is the concept of an added separate behavior layer, advocates of the paradigm generally subscribe to a number of related principles, such as:

  • DOM Scripting, i.e. adherence to the W3C DOM and event model, and avoidance of browser-specific extensions (except when really necessary, because of bugs or lacking implementations)
  • Capability detection, i.e. testing for specific functionality before it is used[10]. In particular this is seen as the opposite of browser detection.
  • More generally, JavaScript best practices often parallel those in other programming languages, such as encapsulation and abstraction layers, avoidance of global variables, meaningful naming conventions, use of appropriate design patterns, and systematic testing. Such principles are essential to large-scale software development, but have not been widely observed in JavaScript programming in the past; their adoption is seen as an essential component of JavaScript's transition from a "toy" language to a tool for serious development.

See also


ar:جافا سكريبت المخفية

es:JavaScript no obstructivo fr:Javascript discret ru:Ненавязчивый JavaScript

Personal tools

Served in 0.386 secs.