Unobtrusive Javascript 1 Unobtrusive Javascript

Unobtrusive Javascript 1 Unobtrusive Javascript

Unobtrusive JavaScript 1 Unobtrusive JavaScript Part of a series on JavaScript • JavaScript syntax • JavaScript library • Unobtrusive JavaScript Unobtrusive JavaScript is a general approach to the use of JavaScript in web pages. 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] A new paradigm JavaScript historically has had a reputation for being 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 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;[6] scripts often failed completely in some browsers. The recent emergence of standards-compliant browsers, JavaScript frameworks and high-quality debugging tools have made organized, scalable JavaScript code possible, and the emergence of Ajax interfaces has made it desirable. 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 concept of unobtrusiveness in relation to JavaScript programming was coined in 2002 by Stuart Langridge[7] in the article "Unobtrusive DHTML, and the power of unordered lists [8]".[9] 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[10] and article format.[11] 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 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. Unobtrusive JavaScript 2 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.[12] 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 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, 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: <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 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: <input type="text" name="date" id="date" /> 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: window.onload = function() { document.getElementById('date').onchange = validateDate; }; Unobtrusive JavaScript 3 Namespaces 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 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 language.[13] 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 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 namespace and cannot interfere with or intrude upon any other code at any time. Unobtrusive JavaScript 4 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 can simplify this process and help ensure that individual browser and browser version implementation details are hidden 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

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    6 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us