Unobtrusive JavaScript is a general approach to using JavaScript in web pages . Though the term is not formally defined, its basic principles are understood to include:

  • Separation of functionality (the “behavior layer”) from a Web site’s structure / content and presentation [1]
  • Best practices to avoid the problems of the traditional JavaScript programming (such as browser inconsistencies and lack of scalability )
  • Progressive enhancement to supporting user agents That May not supporting advanced JavaScript functions [2]

A new paradigm

JavaScript historically has a reputation for being a clumsy language unsuitable for serious application development. [3] [4] This document has been widely used by the Document Object Model (DOM) [5] in various browsers, and the general use of buggy copy-and-paste code. Runtime errors were so common (and so difficult to debug) that few programmers ever tried to fix them; [6] often failed scripts completely in some browsers.

Some web developers have been promoting graceful degradation since 1994. [7]

The recent emergence of standard-compliant browsers , JavaScript frameworks, and high-quality debugging tools have been organized, scalable JavaScript code possible, and the emergence of Ajax interfaces has made it desirable. Whereas JavaScript Was once reserved for single Relatively and non-critical tasks Such As form validation and decorative novelties, it is now used to write off being white, complex codebases That are Often hand of a website’s core functionality. Run time errors and unpredictable behavior are no minor Annoyances along; they are fatal flaws.

Advocates of unobtrusive JavaScript see it as larger share of the Web standards movement; much as the demand for cross-browser compatibility HAS driven the Increasing emphasis is standardized markup and style , the Increasing demand for rich Internet applications 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 [8] in the article ” Unobtrusive DHTML, and the power of unordered lists “. [9]In the article Langridge argues for JavaScript, including event handlers, outside of the HTML. Stuart Langridge [10] and article format. [11]

Unobtrusive paradigm. David Flanagan’s seminal JavaScript: The Definitive Guide says there are no specific formulas, 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 JavaScript running.
  3. Unobtrusive JavaScript should not degrade the accessibility of the HTML, and ideally should improve it. [12]

The Web Standards Project describes the benefits of a DOM scripting in their JavaScript Manifesto .

  1. Usability: An unobtrusive DOM script does not draw the attention of the user.
  2. Graceful degradation: Unobtrusive DOM scripts never generate error messages, in any browser, even when they fail. If features can not be properly presented, 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. [13]

For the Paris Web Conference in 2007, Christian Heilmann identified seven rules of Unobtrusive JavaScript.

  1. Do not make any assumptions: Defensive programming techniques should be possible, the HTML may not have changed, the HTML may not have changed, or the HTML may have changed. 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, especially how they fail, what they make, and unusual configurations or uses.
  5. Understand events , including how they ‘bubble’ and the features of the Eventobject that is passed to most event handlers.
  6. Global functions and variable names.
  7. Work for the next developer by using self-explanatory variables and function names, creating logical and readable code, making dependencies [14]

Separation of behavior from markup

Traditionally, JavaScript has been placed inline together with an HTML document’s markup. For example, the following is a typical way to a JavaScript event handler in HTML:

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

The purpose of HTML markup is to describe a document’s structure, not its programmatic behavior. Combining the two can negatively impact a site’s maintainability, like combining content and presentation . [15] One of several elements in the HTML interface, where the same event handler on multiple elements, when using event delegation .

The unobtrusive solution is programmatically, rather than inline. Rather than adding an onchangeattribute explicitly to the above, the relevant element (s) are simply identified, for example classidor some other means in the markup:

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

A script that runs when the page is first loaded into the browser.

window . addEventListener ( "DOMContentLoaded" , function ( event ) {
 paper . getElementById ( 'date' ). addEventListener ( "change" , validateDate );


Unobtrusive JavaScript should add as little as possible to the global object or global namespace of the environment in which it runs. Other scripts may be overridden, or may be created in the global namespace, and may be 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, reversed dotted segments, as a global single name to publish That Is very Likely to be one, in the style Developed in the Java language. [16]

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." );

Variables while, functions and objects of all kinds can be further Top defined Within Such namespace objects, it is usually recommended to use closures dans le namespace to further Top isolate 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 could be followed directly by the following: [14]

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

org . example . Highlight . goBlue ();
var h = org . example . Highlight ;
h . goGreen ();

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

Degrading gracefully

Writing an event listener that can help you to understand the HTML page and more details. The use of client-side JavaScript libraries such as jQuery , MooTools or Prototype can simplify this process and help ensure that individual browser and browser version implementation details are hiddenand catered for. Keeping most of the JavaScript out of the default namespace helps ensure that it is as unobtrusive as possible in that sense. JavaScript code altogether JavaScript is not available for this language altogether. [12]

This requirement is a basic tenet of web accessibility , to ensure that all users – regardless of their computing platform – get access to the site’s information and functionality. Sometimes there is extra work involved in providing this, but web accessibility is not optional in many countries. For example, in the UK, the Equality Act 2010 , makes it illegal to discriminate against people, and makes it illegal to discriminate against people. [17] While a lot of effort can be made and slickclient-side user interface in unobtrusive JavaScript, it will not remain unobtrusive to a user without client-side scripting if they find that they can not access published information. To meet this goal, it is often necessary to implement equivalent, albeit clunkier, server-side functionality that will be available with JavaScript.

Take, for example, a webpage where thumbnail images need JavaScript is not available in English. First, server-side markup should ensure that the full-size image is served to users without JavaScript. In this case the basic HTML markup may look like the following, for each thumbnail:

< A href = "fullsize-image-001.png" class="manual-link" title = "Click for fullsize picture" >
 < img src = "picture-001-thumb.png" class="thumb" width = "50" height = "50" alt = "Image 1 shows ... etc" >
</ a >

This will work as it is without JavaScript. Unobtrusive JavaScript, in this case, while page-load, could find all the aelements that have a class of manual-linkand remove them from the DOM page. It Could Then find all the pictures of class thumband attach year onmouseoveror year onclickevent handler That Is specified in-line to Provide the slick behavior. For example, when invoking divexisting data , then add to the page DOM invoking existing CSS so it appears in front of existing content, which can be partially grayed out. Teadivwill need a close button, perhaps a ‘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 divfor 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

The essence of unobtrusive JavaScript is the concept of an additional distinct behavior layer, advocates of the paradigm generally subscribe to a number of related principles, such as:

  • DOM Scripting , ie adherence to the W3C DOM and event model, and avoidance of browser-specific extensions.
  • Capability detection , ie testing for specific functionality before it is used. [18] In particular this is seen as the opposite of browser detection.
  • More generally, such as encapsulation and abstraction layers , the avoidance of global variables , the meaningful naming conventions , the use of appropriate design patterns , and the 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

  • Graceful degradation
  • Progressive enhancement


  1. Jump up^ Keith, Jeremy (2006-06-20). “Behavioral Separation” .
  2. Jump up^ Olsson, Tommy (2007-02-06). “Graceful Degradation & Progressive Enhancement” .
  3. Jump up^ Crockford, Douglas (2007-01-24). “The JavaScript Programming Language” .
  4. Jump up^ Crockford, Douglas (2006-11-27). “Advanced JavaScript” .
  5. Jump up^ Crockford, Douglas (2006-10-20). “An Inconvenient API: The Theory of the Dom” .
  6. Jump up^ Crockford, Douglas (2007-06-08). “JavaScript: The Good Parts” .
  7. Jump up^ Aaron Gustafson. “Understanding Progressive Enhancement”. 2008.
  8. Jump up^ “Building dynamic websites” . 2006-08-09 . Retrieved 2010-05-18 .
  9. Jump up^ Langridge, Stuart (November 2002). “Unobtrusive DHTML, and the power of unordered lists” . Retrieved 2008-08-07 .
  10. Jump up^ Langridge, Stuart (2005). DHTML Utopia: Modern Web Design Using JavaScript & DOM . SitePoint. ISBN 0-9579218-9-6 . (Reference to the first edition, since it shows how the author pioneered the concept.)
  11. Jump up^ Eg:Langridge, Stuart (2005-06-01). “DHTML Utopia: Modern Web Design Using JavaScript & DOM” . Retrieved 2016-10-18 .
  12. ^ Jump up to:b Flanagan, David (2006). JavaScript: The Definitive Guide (5th ed.). O’Reilly & Associates. p. 241. ISBN 0-596-10199-6 .
  13. Jump up^ “The JavaScript Manifesto” . The Web Standards Project . Retrieved 8 Feb 2011 .
  14. ^ Jump up to:b Heilmann, Christian (2007). “The seven rules of Unobtrusive JavaScript” . Retrieved 8 Feb 2011 .
  15. Jump up^ “The web standard model – HTML CSS and JavaScript” . W3C Web Standards Curriculum . W3C. 2014 . Retrieved 16 May 2016 .
  16. Jump up^ Flanagan, David (2006). “10”. JavaScript: The Definitive Guide (5th ed.). O’Reilly & Associates. ISBN 0-596-10199-6 .
  17. Jump up^ “Equality Act 2010” . Her Majesty’s Stationery Office . Retrieved 7 September 2011 .
  18. Jump up^ “Dev.Opera – Using Capability Detection” . Retrieved 19 October 2016.