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[1]
- Best practices to avoid the problems of traditional JavaScript programming (such as browser inconsistencies and lack of scalability)
- Progressive enhancement to support user agents that may not support advanced JavaScript functionality[2]
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:
$(document).ready(function(){
$('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
References
- ↑ Keith, Jeremy (2006-06-20). "Behavioral Separation". http://www.alistapart.com/articles/behavioralseparation.
- ↑ Olsson, Tommy (2007-02-06). "Graceful Degradation & Progressive Enhancement". http://accessites.org/site/2007/02/graceful-degradation-progressive-enhancement/.
- ↑ Crockford, Douglas (2007-01-24). "The JavaScript Programming Language". http://yuiblog.com/blog/2007/01/24/video-crockford-tjpl/.
- ↑ Crockford, Douglas (2006-11-27). "Advanced JavaScript". http://yuiblog.com/blog/2006/11/27/video-crockford-advjs/.
- ↑ Crockford, Douglas (2006-10-20). "An Inconvenient API: The Theory of the Dom". http://yuiblog.com/blog/2006/10/20/video-crockford-domtheory/.
- ↑ Crockford, Douglas (2007-06-08). "JavaScript: The Good Parts". http://yuiblog.com/blog/2007/06/08/video-crockford-goodstuff/.
- ↑ Langridge, Stuart (2002-11). "Unobtrusive DHTML, and the power of unordered lists". http://www.kryogenix.org/code/browser/aqlists/. Retrieved 2008-08-07.
- ↑ 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.)
- ↑ Eg: Langridge, Stuart (2005-06-01). "DHTML Utopia: Modern Web Design Using JavaScript & DOM". http://articles.sitepoint.com/article/dhtml-utopia-modern-web-design. Retrieved 2000-11-03.
- ↑ http://dev.opera.com/articles/view/using-capability-detection/
ar:جافا سكريبت المخفية es:JavaScript no obstructivo fr:Javascript discret ru:Ненавязчивый JavaScript
If you like SEOmastering Site, you can support it by - BTC: bc1qppjcl3c2cyjazy6lepmrv3fh6ke9mxs7zpfky0 , TRC20 and more...