Unobtrusive JavaScript

Unobtrusive JavaScript

"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:

* Separation of functionality (the "behavior layer") from a Web page's structure/content and presentation
* Best practices to avoid the problems of traditional JavaScript programming (such as browser inconsistencies and lack of scalability)
* Graceful degradation in browsers where the advanced JavaScript functionality will not work as desired

The need for a new paradigm

JavaScript has long had a reputation as a clumsy, hackish language unsuitable for serious application development. This has been largely due to inconsistent implementations of the language itself and the Document Object Model in various browsers, and the widespread use of buggy cut-and-paste code written by amateurs. 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; 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 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. Runtime errors and unpredictable behavior are no longer minor annoyances; they are fatal flaws.

Unobtrusive JavaScript can be seen 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 the more robust methods of unobtrusive JavaScript. The term was invented in the 2002 by Stuart Langridge. [cite web
url=http://www.kryogenix.org/code/browser/aqlists/
title=Unobtrusive DHTML, and the power of unordered lists
last=Langridge
first=Stuart
date=2002-11
accessdate=2008-08-07
]

eparation 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:

However, the purpose of markup is to describe a document's structure, not its programmatic behavior. Combining the two negatively impacts a site's maintainability for the same reason that combining content and presentation does: if a site contains hundreds of such date fields, adding the appropriate onchange attribute for each one (and modifying them later, if necessary) can be a labor-intensive process. Furthermore, inline syntax prevents the registration of more than one event handler for the element's onchange event, which can be a problem as the application grows.

The unobtrusive solution is to register the necessary event handlers programmatically, rather than inline. This is commonly achieved by assigning a particular CSS selector to all elements which need to be acted upon by the script:

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

Using native JavaScript:window.onload = function(){ //Wait for the page to load. var inputs = document.getElementsByTagName('input'), input; for(var i=0,l=inputs.length;i;

The following script is specific to the jQuery JavaScript library:$(document).ready(function(){ //Wait for the page to load. $('input [name=date] ').bind('change', validateDate);});

function validateDate(){ //Do something when the content of the 'input' element with the name 'date' is changed.}

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.

The following script is specific to the MooTools JavaScript library:window.addEvent("domready",function() { //code here will be executed when the dom has loaded})

Best practices

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

* Strict adherence to the W3C DOM and event model, and avoidance of browser-specific extensions.
* 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.

ee also

* Web 2.0
* Ajax
* AJILE
* FDJS - functional, declarative javascript
* Progressive Enhancement

External links

* [http://code.google.com/p/components-js/ Components] an unobtrusive JavaScript framework
* [http://adactio.com/atmedia2005/ The Behaviour Layer: Using JavaScript for good, not evil]
* [http://onlinetools.org/articles/unobtrusivejavascript/ Unobtrusive JavaScript]
* [http://alistapart.com/articles/behavioralseparation A List Apart: Behavioral Separation]
* [http://www.ujs4rails.com/ Unobtrusive JavaScript] plugin for Ruby on Rails
* [http://railsenvy.com/2008/1/3/unobtrusive-javascript Unobtrusive Javascript Presentation] - Background and overview
* [http://ajile.iskitz.com/ AJILE, A JavaScript module that supports Unobtrusive JavaScript development]
* [http://www.bennolan.com/behaviour/ Behaviour] , a JavaScript class library intended to facilitate unobtrusive JavaScript development
* [http://code.google.com/p/fdjs fdjs] , functional declarative javascript programming
* [http://trac.symfony-project.com/wiki/sfUJSPlugin Unobtrusive JavaScript Plugin] for the Symfony PHP framework
* [http://www.quirksmode.org/ Quirksmode: Examples of how to write unobtrusive javascript]

References


Wikimedia Foundation. 2010.

Игры ⚽ Поможем написать реферат

Look at other dictionaries:

  • Unobtrusive JavaScript — (wörtl. unaufdringliches JavaScript, auch: barrierefreies JavaScript) ist ein Konzept für eine zeitgemäße Verwendung von JavaScript in Webseiten. Javascript soll demnach eine Erweiterung des Funktionsumfangs bieten anstatt einer Voraussetzung.… …   Deutsch Wikipedia

  • Javascript Discret — Le javascript discret (Unobtrusive Javascript) est une pratique dans la programmation informatique en javascript. Cette pratique n est pas décrite par une norme. Cette pratique consiste en la séparation du code html et du javascript. Origine de… …   Wikipédia en Français

  • JavaScript syntax — This article is part of the JavaScript series. JavaScript JavaScript syntax JavaScript topics This box: view · …   Wikipedia

  • Javascript discret — Le JavaScript discret (Unobtrusive JavaScript) est une pratique dans la programmation informatique en JavaScript. Cette pratique n est pas décrite par une norme. Cette pratique consiste en la séparation du code HTML et du JavaScript. Origine de… …   Wikipédia en Français

  • Ненавязчивый JavaScript — (англ. Unobtrusive JavaScript) является относительно новой техникой в программировании на языке JavaScript, используемой в Вебе. Этот термин был изобретен в 2002 году Стюартом Лэнгриджем.[1] Хотя он официально не определён, под его… …   Википедия

  • UJS — Javascript discret Le javascript discret (Unobtrusive Javascript) est une pratique dans la programmation informatique en javascript. Cette pratique n est pas décrite par une norme. Cette pratique consiste en la séparation du code html et du… …   Wikipédia en Français

  • Barrierefreies Internet — sind Web Angebote, die von allen Nutzern unabhängig von körperlichen oder technischen Möglichkeiten uneingeschränkt (barrierefrei) genutzt werden können. Die Nutzung des Begriffs Internet ist hier eine umgangssprachliche Gleichsetzung des… …   Deutsch Wikipedia

  • Progressive enhancement — is a strategy for web design that emphasizes accessibility, semantic markup, and external stylesheet and scripting technologies. Progressive enhancement uses web technologies in a layered fashion that allows everyone to access the basic content… …   Wikipedia

  • Dynamic HTML — HTML HTML and HTML5 Dynamic HTML XHTML XHTML Mobile Profile and C HTML Canvas element Character encodings Document Object Model Font family HTML editor HTML element HTML Frames HTML5 video …   Wikipedia

  • Eolas — Type Technology Founded 1994 Founder(s) Michael David Doyle Headquarters Tyler, TX, United States …   Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”