Unobtrusive JavaScript
Encyclopedia
"Unobtrusive JavaScript" is a general approach to the use of JavaScript
JavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....

 in web page
Web page
A web page or webpage is a document or information resource that is suitable for the World Wide Web and can be accessed through a web browser and displayed on a monitor or mobile device. This information is usually in HTML or XHTML format, and may provide navigation to other web pages via hypertext...

s. Though the term is not formally defined, its basic principles are generally understood to include:
  • Separation
    Separation of concerns
    In computer science, separation of concerns is the process of separating a computer program into distinct features that overlap in functionality as little as possible. A concern is any piece of interest or focus in a program. Typically, concerns are synonymous with features or behaviors...

     of functionality (the "behavior layer") from a Web page's structure/content
    Markup language
    A markup language is a modern system for annotating a text in a way that is syntactically distinguishable from that text. The idea and terminology evolved from the "marking up" of manuscripts, i.e. the revision instructions by editors, traditionally written with a blue pencil on authors' manuscripts...

     and presentation
  • Best practices to avoid the problems of traditional JavaScript programming (such as browser
    Web browser
    A web browser is a software application for retrieving, presenting, and traversing information resources on the World Wide Web. An information resource is identified by a Uniform Resource Identifier and may be a web page, image, video, or other piece of content...

     inconsistencies and lack of scalability
    Scalability
    In electronics scalability is the ability of a system, network, or process, to handle growing amount of work in a graceful manner or its ability to be enlarged to accommodate that growth...

    )
  • Progressive enhancement
    Progressive enhancement
    Progressive enhancement is a strategy for web design that emphasizes accessibility, semantic HTML markup, and external stylesheet and scripting technologies...

     to support user agents that may not support advanced JavaScript functionality

A new paradigm

JavaScript historically has had a reputation for being 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
Document Object Model
The Document Object Model is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents. Aspects of the DOM may be addressed and manipulated within the syntax of the programming language in use...

 in various browsers, and the widespread use of buggy
Software bug
A software bug is the common term used to describe an error, flaw, mistake, failure, or fault in a computer program or system that produces an incorrect or unexpected result, or causes it to behave in unintended ways. Most bugs arise from mistakes and errors made by people in either a program's...

 copy-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; scripts often failed completely in some browsers.

The recent emergence of standards-compliant browsers
Web standards
Web standards is a general term for the formal standards and other technical specifications that define and describe aspects of the World Wide Web. In recent years, the term has been more frequently associated with the trend of endorsing a set of standardized best practices for building web sites,...

, JavaScript frameworks and high-quality debugging tools have made organized, scalable JavaScript code possible, and the emergence of Ajax
Ajax (programming)
Ajax is a group of interrelated web development methods used on the client-side to create asynchronous web applications...

 interfaces has made it desirable. Whereas JavaScript was once reserved for relatively simple and non-critical tasks such as form validation
Data validation
In computer science, data validation is the process of ensuring that a program operates on clean, correct and useful data. It uses routines, often called "validation rules" or "check routines", that check for correctness, meaningfulness, and security of data that are input to the system...

 and decorative novelties, it is now being used to write large, complex codebase
Codebase
The term codebase, or code base, is used in software development to mean the whole collection of source code used to build a particular application or component. Typically, the codebase includes only human-written source code files, and not, e.g., source code files generated by other tools or...

s 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
Web standards
Web standards is a general term for the formal standards and other technical specifications that define and describe aspects of the World Wide Web. In recent years, the term has been more frequently associated with the trend of endorsing a set of standardized best practices for building web sites,...

 movement; much as the demand for cross-browser compatibility has driven the increasing emphasis on standardized markup and style
Cascading Style Sheets
Cascading Style Sheets is a style sheet language used to describe the presentation semantics of a document written in a markup language...

, the increasing demand for rich Internet application
Rich Internet application
A Rich Internet Application is a Web application that has many of the characteristics of desktop application software, typically delivered either by way of a site-specific browser, via a browser plug-in, independent sandboxes, extensive use of JavaScript, or virtual machines...

s is driving the movement toward better practices with the use of JavaScript. The concept of Unobtrusiveness in relation to JavaScript programming was coined in 2002 by Stuart Langridge
Stuart Langridge
Stuart Langridge is the author of two books for technical publisher SitePoint, DHTML Utopia, and Run Your Own Web Server Using Linux & Apache as well as writing the Stylish Scripting weblog during 2005...

 in the article "Unobtrusive DHTML, and the power of unordered lists". In the article Langridge 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 and article format.

Other authors have tried to refine and define the essential elements of the unobtrusive paradigm. David Flanagan's seminal JavaScript: The Definitive Guide says that while there is no specific formula, there are three main goals: (1) to separate JavaScript from HTML markup, as well as keeping modules of JavaScript independent of other modules. (2) Unobtrusive JavaScript should degrade gracefully - all content should be available without all or any of the JavaScript running successfully. (3) Unobtrusive JavaScript should not degrade the accessibility of the HTML, and ideally should improve it, whether the user has personal disabilities or are using an unusual, or unusually configured, browser.

The Web Standards Project
Web Standards Project
The Web Standards Project is a group of professional web developers dedicated to disseminating and encouraging the use of the web standards recommended by the World Wide Web Consortium, along with other groups and standards bodies....

 describes four benefits of unobtrusive DOM scripting in their JavaScript Manifesto. (1) Usability: An unobtrusive DOM script does not draw the attention of the user - visitors use it without thinking about it. (2) Graceful degradation: Unobtrusive DOM scripts never generate error messages, in any browser, even when they fail. If features cannot be presented properly, they silently disappear. (3) Accessibility: If any script fails, the page still delivers its core functions and information via the markup, stylesheets and/or server-side scripting. (4) Separation: For the benefit of other and future web developers, all JavaScript code is maintained separately, without impacting other files of script, markup or code.

For the Paris Web Conference in 2007, Christian Heilmann identified seven rules of Unobtrusive JavaScript. (1) Do not make any assumptions: Defensive programming
Defensive programming
Defensive programming is a form of defensive design intended to ensure the continuing function of a piece of software in spite of unforeseeable usage of said software. The idea can be viewed as reducing or eliminating the prospect of Murphy's Law having effect...

 techniques should allow for the possibilities that JavaScript may not run, the browser may not support expected methods, the HTML may have changed, unexpected input devices may be in use and other scripts may either not be present or may be encroaching on the global namespace. (2) Find your hooks and relationships, such as IDs and other aspects of the expected HTML. (3) Leave traversing individual DOM objects to the experts, such as to the CSS handler built into the browser where possible. (4) Understand browsers and users, particularly how they fail, what assumptions they make, and unusual configurations or usages. (5) Understand events
DOM Events
DOM events allow event-driven programming languages like JavaScript, JScript, ECMAScript, VBScript and Java to register various event handlers/listeners on the element nodes inside a DOM tree, e.g. HTML, XHTML, XUL and SVG documents....

, including how they 'bubble' and the features of the Event object that is passed to most event handlers. (6) Play well with other scripts by avoiding global function and variable names. (7) Work for the next developer by using self-explanatory variable and function names, creating logical and readable code, making dependencies obvious, and commenting any code that still might confuse.

Separation of behavior from markup

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





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
Separation of presentation and content
Separation of presentation and content is a common idiom, a design philosophy, and a methodology applied in the context of various publishing technology disciplines, including information retrieval, template processing, web design, web development, word processing, desktop publishing,...

 does. They also argue that inline event handlers are harder to use and maintain, when one needs to set handlers for several events on a single element, when one wants to set the same event handler on several elements, 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. Rather than adding the onchange attribute explicitly as above, the relevant element(s) are simply identified, for example by class, id or some other means in the markup:





A script that runs when the page is first loaded into the browser can then look for the relevant element(s) and set them up accordingly:

For example, using native JavaScript, HTML5 events and DOM Level 2 event listeners:

// DOMContentLoaded will fire when the DOM is loaded but unlike "load" it does not wait for images, etc.
// It is being standardized in HTML5
document.addEventListener('DOMContentLoaded', function {
document.getElementById('date').addEventListener('change', validateDate, false);
}, false);

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


The above example will not work in all browsers; some – particularly Internet Explorer
Internet Explorer
Windows Internet Explorer is a series of graphical web browsers developed by Microsoft and included as part of the Microsoft Windows line of operating systems, starting in 1995. It was first released as part of the add-on package Plus! for Windows 95 that year...

 (including version 8) – do not support DOM 2 event listeners. In practice developers often use libraries to abstract
Abstraction (computer science)
In computer science, abstraction is the process by which data and programs are defined with a representation similar to its pictorial meaning as rooted in the more complex realm of human life and language with their higher need of summarization and categorization , while hiding away the...

 away browser inconsistencies and deficiencies. The following script is specific to the MooTools
MooTools
MooTools is a lightweight, object-oriented, web-application framework for JavaScript, written in JavaScript. It is released under the free, open-source MIT License...

 JavaScript library, but accomplishes the same setup:

window.addEvent('domready', function {
$('date').addEvent('change', validateDate);
});


The following script is specific to the jQuery
JQuery
jQuery is a cross-browser JavaScript library designed to simplify the client-side scripting of HTML. It was released in January 2006 at BarCamp NYC by John Resig...

 JavaScript library:

$(function {
$('#date').change(validateDate);
});


As it uses id, or other valid attributes and characteristics of the markup, this approach is consistent with modern standards-based markup practices
W3C recommendation
A W3C Recommendation is the final stage of a ratification process of the World Wide Web Consortium working group concerning a technical standard. This designation signifies that a document has been subjected to a public and W3C-member organization's review. It aims to standardise the Web technology...

.

Namespaces

Unobtrusive JavaScript should add as little as possible to the global object
Object (computer science)
In computer science, an object is any entity that can be manipulated by the commands of a programming language, such as a value, variable, function, or data structure...

 or global namespace
Namespace (computer science)
A namespace is an abstract container or environment created to hold a logical grouping of unique identifiers or symbols . An identifier defined in a namespace is associated only with that namespace. The same identifier can be independently defined in multiple namespaces...

 of the environment in which it runs. Other scripts may override any variable or function that is created in the global namespace, and this can lead to unexpected failures that are difficult to debug. JavaScript does not have a built-in explicit namespace mechanism, but the desired effects are easy to produce using the language's facilities. Flanagan suggests the use of the developer's own domain name, dotted segments reversed, as a single global name to publish that is very likely to be unique, in the style developed in the Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

 language.

var org;
if (!org) {
org = {};
} else if (typeof org != 'object') {
throw new Error("org already exists and is not an object");
}
if (!org.example) {
org.example = {};
} else if (typeof org.example != 'object') {
throw new Error("org.example already exists and is not an object");
}

While variables, functions and objects of all kinds can be further defined within such namespace objects, it is usually recommended to use closures within the namespace to further isolate
Information hiding
In computer science, information hiding is the principle of segregation of the design decisions in a computer program that are most likely to change, thus protecting other parts of the program from extensive modification if the design decision is changed...

 what will become private variables and functions, as well as to export what will be the public interface of each module of functionality. The code above could be followed directly by the following:

org.example.Highlight = function {
// define private data and functions
var highlightId = 'x';
function setHighlight(color) {
document.getElementById(highlightId).style.color = color;
}

// return public pointers to functions or properties
// that are to be public
return {
goGreen: function { setHighlight('green'); },
goBlue: function { setHighlight('blue'); }
}
}; //end closure definition and invoke it


From any other module, these public methods could be invoked in either way as follows

org.example.Highlight.goBlue;

var h = org.example.Highlight;
h.goGreen;


In this way, each module-writer's code is contained in private or in a unique a namespace and cannot interfere with or intrude upon any other code at any time.

Degrading gracefully

Writing an event listener that detects the loading of the HTML page and then adds relevant listeners to other events on the page, as well as other behaviors as required, can solve the problem of separating JavaScript functionality from HTML markup. The use of client-side JavaScript libraries such as jQuery, MooTools or Prototype
Prototype Javascript Framework
The Prototype JavaScript Framework is a JavaScript framework created by Sam Stephenson in February 2005 as part of the foundation for Ajax support in Ruby on Rails. It is implemented as a single file of JavaScript code, usually named prototype.js...

 can simplify this process and help ensure that individual browser and browser version implementation details are hidden
Abstraction (computer science)
In computer science, abstraction is the process by which data and programs are defined with a representation similar to its pictorial meaning as rooted in the more complex realm of human life and language with their higher need of summarization and categorization , while hiding away the...

 and catered for. Keeping most of the JavaScript out of the default namespace helps ensure that it is as unobtrusive as possible in that sense. A further criterion of unobtrusive Javascript that is often cited is to ensure that added behavior degrades gracefully on those browsers with unexpected configurations, and those on which the user may have disabled JavaScript altogether.

This requirement is a basic tenet of web accessibility
Web accessibility
Web accessibility refers to the inclusive practice of making websites usable by people of all abilities and disabilities. When sites are correctly designed, developed and edited, all users can have equal access to information and functionality...

, to ensure that JavaScript-enhanced websites are not only usable by people of all abilities and disabilities but that all users - whatever their computing platform - get equal access to all the site's information and functionality. Sometimes there is extra work involved in achieving this, but web accessibility is not an optional extra in many countries. For example in the UK, the Equality Act 2010, while it does not refer explicitly to website accessibility, makes it illegal to discriminate against people with disabilities and applies to anyone providing any service in the public, private and voluntary sectors. While a lot of effort may be put into designing and implementing a slick client-side
Client-side
Client-side refers to operations that are performed by the client in a client–server relationship in a computer network.Typically, a client is a computer application, such as a web browser, that runs on a user's local computer or workstation and connects to a server as necessary...

 user interface in unobtrusive JavaScript, it will not remain unobtrusive to a user without client-side scripting if they find that they cannot access published information. To meet this goal, it is often necessary to implement equivalent, albeit clunkier, server-side
Server-side
Server-side refers to operations that are performed by the server in a client–server relationship in computer networking.Typically, a server is a software program, such as a web server, that runs on a remote server, reachable from a user's local computer or workstation...

 functionality that will be available without the use of JavaScript at all.

Take, for example, a webpage where thumbnail images have JavaScript behaviours so that full-size images appear in front of the page when the mouse is rolled over them or they are clicked. Server-side markup should be available and maintained so that the relevant full-size image is served as a new page to users without JavaScript who click on the image. In this case the basic HTML markup may look like the following, for each thumbnail:



Image 1 shows... etc



This will work as it is without JavaScript, provided the page fullsize-image-001.html exists and is maintained. Unobtrusive JavaScript, in this case, during page-load, could find all the a elements that have a class of manual-link and remove them from the page DOM. It could then find all the images of class thumb and attach an on-mouseover or an on-click event handler that is specified in-line to provide the slick behaviour. For example, when invoked the event handler may send an AJAX
Ajax
- Mythology :* Ajax , son of Telamon, ruler of Salamis and a hero in the Trojan War, also known as "Ajax the Great"* Ajax the Lesser, son of Oileus, ruler of Locris and the leader of the Locrian contingent during the Trojan War.- People :...

 request to the server for the full-size image, then add a div to the page DOM invoking existing CSS
CSS
-Computing:*Cascading Style Sheets, a language used to describe the style of document presentations in web development*Central Structure Store in the PHIGS 3D API*Closed source software, software that is not distributed with source code...

 so it appears in front of existing content, which itself may become partially greyed out. The div will need a close button, perhaps a visual 'spinner' to show that data is loading, etc. Finally, when the AJAX data arrives, the handler hides the spinner and inserts the full-size image into the new div for display.

This way, all the client-side functionality depends on the same JavaScript function. If that function succeeds, it begins by removing the basic, manual behavior, and goes on to add the client-side scripted behavior. If the script fails for whatever reason, the manual behavior remains in place and remains functional.

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
    DOM scripting
    The term DOM scripting refers to programmatically accessing the Document Object Model . In common usage, DOM scripting implies JavaScript. DOM scripting has its roots in Dynamic HTML , but is more structured. It is the third pillar in the web standards movement.-DHTML vs...

    , i.e. adherence to the W3C
    World Wide Web Consortium
    The World Wide Web Consortium is the main international standards organization for the World Wide Web .Founded and headed by Tim Berners-Lee, the consortium is made up of member organizations which maintain full-time staff for the purpose of working together in the development of standards for the...

     DOM
    Document Object Model
    The Document Object Model is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents. Aspects of the DOM may be addressed and manipulated within the syntax of the programming language in use...

     and event model, and avoidance of browser-specific extensions (except when really necessary, because of bugs or lacking implementations)
  • Capability detection
    Progressive enhancement
    Progressive enhancement is a strategy for web design that emphasizes accessibility, semantic HTML markup, and external stylesheet and scripting technologies...

    , i.e. testing for specific functionality before it is used. 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
    Information hiding
    In computer science, information hiding is the principle of segregation of the design decisions in a computer program that are most likely to change, thus protecting other parts of the program from extensive modification if the design decision is changed...

     and abstraction layer
    Abstraction layer
    An abstraction layer is a way of hiding the implementation details of a particular set of functionality...

    s, avoidance of global variable
    Global variable
    In computer programming, a global variable is a variable that is accessible in every scope . Interaction mechanisms with global variables are called global environment mechanisms...

    s, meaningful naming conventions
    Naming conventions (programming)
    In computer programming, a naming convention is a set of rules for choosing the character sequence to be used for identifiers which denote variables, types and functions etc...

    , use of appropriate design patterns
    Design Patterns
    Design Patterns: Elements of Reusable Object-Oriented Software is a software engineering book describing recurring solutions to common problems in software design. The book's authors are Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides with a foreword by Grady Booch. The authors are...

    , and systematic testing
    Software testing
    Software testing is an investigation conducted to provide stakeholders with information about the quality of the product or service under test. Software testing can also provide an objective, independent view of the software to allow the business to appreciate and understand the risks of software...

    . 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.

Criticism and responses

Unobtrusive JavaScript can take longer to develop and can be harder to read through later on as one would need to reference external code to find if an object is tied to any events.
The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK