Jump to content

Unobtrusive JavaScript: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
Undid revision 1031446794 by Anton.bersh (talk): we are not finished on the talk page; I will be working on this—furthermore, nobody proposed and discussed a merger
Tags: Removed redirect Undo
expanded lead section; trimmed WP:POV & WP:OR material that was complained about on the talk page; added references and #Further reading section; removed links from #See also section that are already in article body per WP:NOTSEEALSO
Line 1: Line 1:
'''Unobtrusive JavaScript''' is a general approach to the use of [[client-side]] [[JavaScript]] in [[web page]]s so that if JavaScript features are partially or fully absent in a user's [[web browser]], then the user notices as little as possible any lack of the web page's JavaScript functionality.<ref name=Langridge2005/> The term has been used by different technical writers to emphasize different aspects of [[front-end web development]]. For some writers, the term has been understood more generally to refer to [[separation of concerns|separation of functionality]] (the "behavior layer") from a web page's [[Markup language|structure/content]] and [[Style sheet (web development)|presentation]],<ref>{{cite web |last=Keith |first=Jeremy |title=Behavioral Separation |date=2006-06-20 |url=https://www.alistapart.com/articles/behavioralseparation |website=www.alistapart.com |access-date=2007-01-27 |quote=Separating out behavior from markup like this is called unobtrusive JavaScript.}}</ref> while other writers have used the term more precisely to refer to the use of [[progressive enhancement]] to support [[user agent]]s that lack certain JavaScript functionality and users that have disabled JavaScript.<ref>{{cite web |last=Olsson |first=Tommy |title=Graceful Degradation & Progressive Enhancement |date=2007-02-06 |url=http://accessites.org/site/2007/02/graceful-degradation-progressive-enhancement/2 |website=accessites.org |archive-url=https://web.archive.org/web/20170517143009/http://accessites.org/site/2007/02/graceful-degradation-progressive-enhancement/2 |archive-date=2017-07-18 |access-date=2009-01-03 |quote=Progressive enhancement when it comes to JavaScript is becoming more common these days. The key to this is known as unobtrusive JavaScript. An unobtrusive script is silently ignored by user agents that do not support it, but is applied by more capable devices. Just like an external style sheet.}}</ref> Following the latter definition, unobtrusive JavaScript contributes to [[web accessibility]] insofar as it helps ensure that that all users—whatever their computing platform—get roughly equal access to all of the web page's information and functionality.<ref name=Flanagan2006/><ref>{{cite book |last=Connor |first=Joshue O. |date=2012 |chapter=Unobtrusive JavaScript |title=Pro HTML5 Accessibility: Building an Inclusive Web |location=Berkeley, CA |publisher=[[Apress]] |pages=[https://books.google.com/books?id=gdithJnztpUC&pg=PA71 71] |isbn=9781430241942 |oclc=757486357 |doi=10.1007/978-1-4302-4195-9_3}}</ref>
{{Update|talk=Is 'Unobtrusive JavaScript' an historic opinion piece?|date=January 2020}}

'''Unobtrusive JavaScript''' is a general approach to the use of [[JavaScript]] in [[web page]]s. Though the term is not formally defined, its basic principles are generally understood to include [[separation of concerns|separation of functionality]] (the "behavior layer") from a Web page's [[Markup language|structure/content]] and [[Style sheet (web development)|presentation]],<ref>{{cite web
|last=Keith
|first=Jeremy
|title=Behavioral Separation
|date=2006-06-20
|url=http://www.alistapart.com/articles/behavioralseparation
}}</ref> and [[progressive enhancement]] to support [[user agents]] that may not support certain JavaScript functionality and users that have disabled JavaScript.<ref>{{cite web
|last=Olsson
|first=Tommy
|title=Graceful Degradation & Progressive Enhancement
|date=2007-02-06
|url=http://accessites.org/site/2007/02/graceful-degradation-progressive-enhancement/
}}</ref>


==Overview==
==Overview==
A typical [[client-side dynamic web page]] can be conceived as consisting of four parts: the [[Markup language|marked-up]] content ([[HTML]]), the style sheet ([[CSS]]), [[client-side JavaScript]], and embedded objects such as images.<ref name=JSBible>{{cite book |last1=Goodman |first1=Danny |author-link1=Danny Goodman |last2=Morrison |first2=Michael |author-link2=Michael Morrison (author) |last3=Novitski |first3=Paul |last4=Rayl |first4=Tia Gustaff |date=2010 |chapter=JavaScript's Role in the World Wide Web and Beyond |title=JavaScript Bible |edition=7th |location=Indianapolis, IN |publisher=Wiley |pages=3–13 |isbn=9780470526910 |oclc=435731997}}</ref>{{rp|5}} The client-side JavaScript part can be conceived as enhancing the other parts by adding features or functionality that would not be possible without JavaScript.<ref name=JSBible/>{{rp|3}}


The concept of "unobtrusiveness" in relation to client-side JavaScript was coined in 2002 by [[Stuart Langridge]]<ref name=Langridge2002>{{cite web |url=http://www.netmag.co.uk/zine/dhtml-1/building-dynamic-websites |title=Building dynamic websites |website=www.netmag.co.uk |date=2006-08-09 |access-date=2010-05-18 |archive-url=https://web.archive.org/web/20101205235951/http://www.netmag.co.uk/zine/dhtml-1/building-dynamic-websites |archive-date=2010-12-05}}<!-- See "about the author" to validate the claim --></ref> in the article "Unobtrusive DHTML, and the power of unordered lists".<ref>{{cite web |url=http://www.kryogenix.org/code/browser/aqlists/ |title=Unobtrusive DHTML, and the power of unordered lists |last=Langridge |first=Stuart |date=November 2002 |access-date=2008-08-07 |website=www.kryogenix.org |archive-url=https://web.archive.org/web/20021204224748/http://www.kryogenix.org/code/browser/aqlists/ |archive-date=2002-12-04 |url-status=live}}</ref> In the article Langridge argued for a way to keep all JavaScript code, including event handlers, outside of the HTML when using [[dynamic HTML]] (DHTML).<ref name=Langridge2002/> He said that the the purpose of this kind of organization of code was "providing a better user experience for people whose browsers can support it, and {{em|not affecting}} those whose browsers cannot", while also making scripting easier for [[web developer]]s.<ref name=Langridge2002/> Langridge later expanded upon this thought and emphasized that the core meaning of "unobtrusive" is that "if a given Web browser doesn't support the DHTML features you're using, that absence should affect the user experience as little as possible".<ref name=Langridge2005>{{cite book |last=Langridge |first=Stuart |title=DHTML Utopia: Modern Web Design Using JavaScript & DOM |location=Collingwood, VIC, Australia |publisher=SitePoint |year=2005 |isbn=9780957921894 |oclc=60690615 |url-access=registration |url=https://archive.org/details/dhtmlutopiamoder0000lang |page=[https://archive.org/details/dhtmlutopiamoder0000lang/page/75 75] |quote=An important design constraint when adding DHTML to your Websites is that it should be unobtrusive. By 'unobtrusive,' I mean that if a given Web browser doesn't support the DHTML features you're using, that absence should affect the user experience as little as possible. Errors should not be shown to the user: the site should be perfectly usable without the DHTML enhancements.}} (Reference to the first edition, since it shows how the author pioneered the concept.) The same passage is in an article excerpted from the book: {{cite web |url=http://articles.sitepoint.com/article/dhtml-utopia-modern-web-design/4 |title=DHTML Utopia: Modern Web Design Using JavaScript & DOM |last=Langridge |first=Stuart |date=2005-06-01 |access-date=2016-10-18 |website=articles.sitepoint.com |archive-url=https://web.archive.org/web/20100421102116/http://articles.sitepoint.com/article/dhtml-utopia-modern-web-design/4 |archive-date=2010-04-21}}</ref> In other words, for Langridge, "unobtrusive" principally refers to users' experience of the absence of JavaScript features in a given situation.<ref name=Langridge2005/>
The emergence of [[Web standards|standards-compliant browsers]], [[JavaScript framework]]s, and high-quality debugging tools made organized, scalable JavaScript code possible, and the emergence of [[Ajax (programming)|Ajax]] interfaces made it desirable. Whereas JavaScript was once reserved for relatively simple and non-critical tasks such as form [[data validation|validation]] and decorative novelties, it is now used to write large, complex [[codebase]]s that are often part of a site's core functionality.


==Variant definitions==
The concept of "unobtrusiveness" in relation to JavaScript programming was coined in 2002 by [[Stuart Langridge]]<ref>{{cite web
Other authors have described variations on the essential elements of unobtrusiveness.
|url=http://www.netmag.co.uk/zine/dhtml-1/building-dynamic-websites
|title= Building dynamic websites
|date=2006-08-09
|access-date=2010-05-18
}}</ref><!-- See "about the author" to validate the claim --> in the article "Unobtrusive DHTML, and the power of unordered lists".<ref>{{cite web
|url=http://www.kryogenix.org/code/browser/aqlists/
|title=Unobtrusive DHTML, and the power of unordered lists
|last=Langridge
|first=Stuart
|date=November 2002
|access-date=2008-08-07
}}</ref> In the article Langridge argued 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<ref>{{cite book |last= Langridge |first= Stuart |title= DHTML Utopia:Modern Web Design Using JavaScript & DOM |publisher= SitePoint |year= 2005 |isbn= 0-9579218-9-6 |url-access= registration |url= https://archive.org/details/dhtmlutopiamoder0000lang }} (Reference to the first edition, since it shows how the author pioneered the concept.)</ref> and article format.<ref>E.g.: {{cite web
|url=http://articles.sitepoint.com/article/dhtml-utopia-modern-web-design
|title=DHTML Utopia: Modern Web Design Using JavaScript & DOM
|last=Langridge
|first=Stuart
|date=2005-06-01
|access-date=2016-10-18
}}</ref>


Other authors have tried to refine and define the essential elements of unobtrusiveness. David Flanagan's book ''JavaScript: The Definitive Guide'' said that while there is no specific formula, there are three main goals:
David Flanagan's book ''JavaScript: The Definitive Guide'' (2006) said that while there is no specific formula, there are three main goals of unobtrusive JavaScript:<ref name=Flanagan2006>{{cite book |last=Flanagan |first=David |chapter=Unobtrusive JavaScript |title=JavaScript: The Definitive Guide |edition=5th |year=2006 |publisher=[[O'Reilly Media]] |isbn=9780596101992 |oclc=64313259 |page=[https://books.google.com/books?id=k0CbAgAAQBAJ&pg=PT262 241–242]}}</ref>
* To separate JavaScript from HTML markup, as well as keeping modules of JavaScript independent of other modules.
* To separate JavaScript from HTML markup, as well as keeping modules of JavaScript independent of other modules using basic conventions such as the use of [[namespace]]s to prevent namespace collisions and the use of module initialization code;
* Unobtrusive JavaScript should degrade gracefully—all content should be available without all or any of the JavaScript running successfully.
* To degrade gracefully—all content should be available without all or any of the JavaScript running successfully;
* 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.<ref name="Flanagan2006">{{cite book |last=Flanagan |first=David |title=JavaScript: The Definitive Guide |url=https://archive.org/details/javascript00libg_297 |url-access=limited |edition=5th |year=2006 |publisher=O'Reilly & Associates |isbn=0-596-10199-6 |page=[https://archive.org/details/javascript00libg_297/page/n239 241]}}</ref>
* To not impede the [[Web accessibility|accessibility of the HTML]], and ideally to improve it, whether the user has personal disabilities or are using an unusual, or unusually configured, browser.


The [[Web Standards Project]], in its ''JavaScript Manifesto'' (2006), said that the "purpose of JavaScript is enhancing the usability of web pages by adding interaction to them", and described four benefits of unobtrusive [[Document Object Model|DOM]] scripting:<ref>{{cite web |url=https://www.webstandards.org/action/dstf/manifesto/ |title=The JavaScript Manifesto |website=www.webstandards.org |publisher=[[Web Standards Project]] |access-date=8 Feb 2011 |archive-url=https://web.archive.org/web/20060614102951/https://www.webstandards.org/action/dstf/manifesto/ |archive-date=2006-06-14 |url-status=live}}</ref>
The [[Web Standards Project]] described four benefits of unobtrusive DOM scripting in their ''JavaScript Manifesto''.
# [[Web usability|Usability]]: An unobtrusive DOM script does not draw the attention of the user—visitors use it without thinking about it.
# [[Web usability|Usability]]: An unobtrusive DOM script does not draw the attention of the user—"visitors just use it without thinking about it."
# [[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.
# [[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.
# [[Web accessibility|Accessibility]]: If any script fails, the page still delivers its core functions and information via the markup, stylesheets and/or server-side scripting.
# [[Web accessibility|Accessibility]]: If any script fails, the page still delivers its core functions and information via the markup, stylesheets and/or server-side scripting.
# [[Separation of concerns|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.<ref>{{cite web | url=http://www.webstandards.org/action/dstf/manifesto/ | title=The JavaScript Manifesto | publisher=The Web Standards Project | access-date=8 Feb 2011}}</ref>
# [[Separation of concerns|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 [[The Web Conference|Web Conference]] in 2007, Christian Heilmann identified seven rules of Unobtrusive JavaScript.<ref name="Heilmann">{{cite web | url=http://icant.co.uk/articles/seven-rules-of-unobtrusive-javascript/ | title=The seven rules of Unobtrusive JavaScript | last=Heilmann | first=Christian | access-date=8 Feb 2011 | year=2007 | archive-url=https://web.archive.org/web/20110502181859/http://icant.co.uk/articles/seven-rules-of-unobtrusive-javascript/ | archive-date=2 May 2011 | url-status=dead | df=dmy-all }}</ref>
For the Paris [[The Web Conference|Web Conference]] in 2007, Christian Heilmann identified seven rules of unobtrusive JavaScript, some of which were wider in scope than other narrower definitions of "unobtrusive":<ref name="Heilmann">{{cite web |url=http://icant.co.uk/articles/seven-rules-of-unobtrusive-javascript/ |title=The seven rules of Unobtrusive JavaScript |last=Heilmann |first=Christian |access-date=8 Feb 2011 |year=2007 |archive-url=https://web.archive.org/web/20110502181859/http://icant.co.uk/articles/seven-rules-of-unobtrusive-javascript/ |website=icant.co.uk |archive-date=2 May 2011 |url-status=dead |df=dmy-all}} See also: {{cite book |last=Heilmann |first=Christian |date=2006 |chapter=Unobtrusive JavaScript |editor1-last=Thatcher |editor1-first=Jim |editor2-last=Burks |editor2-first=Michael R. |editor3-last=Heilmann |editor3-first=Christian |editor4-last=Henry |editor4-first=Shawn Lawton |editor5-last=Kirkpatrick |editor5-first=Andrew |editor6-last=Lauke |editor6-first=Patrick H. |editor7-last=Lawson |editor7-first=Bruce |editor8-last=Regan |editor8-first=Bob |editor9-last=Rutter |editor9-first=Richard |editor10-last=Urban |editor10-first=Mark |title=Web Accessibility: Web Standards And Regulatory Compliance |location=Berkeley, CA |publisher=Friends of Ed; distributed by [[Springer-Verlag]] |pages=[https://books.google.com/books?id=dlJ94KZqwqcC&pg=PA301 301–331] |isbn=1590596382 |doi=10.1007/978-1-4302-0188-5_10}}</ref>
# 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.
# "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.
# Find your hooks and relationships, such as IDs and other aspects of the expected HTML.
# "Find your hooks and relationships", such as IDs and other aspects of the expected HTML.
# Leave traversing individual DOM objects to the experts, such as to the CSS handler built into the browser where possible.
# Leave traversing individual DOM objects to the experts, such as to the CSS handler built into the browser where possible.
# Understand browsers and users, particularly how they fail, what assumptions they make, and unusual configurations or usages.
# "Understand browsers and users", particularly how browsers fail, what assumptions users make, and unusual configurations or usages.
# Understand [[DOM events|events]], including how they 'bubble' and the features of the <code>Event</code> object that is passed to most event handlers.
# "Understand [[DOM events|events]]", including how they 'bubble' and the features of the <code>Event</code> object that is passed to most event handlers.
# Play well with other scripts by avoiding global function and variable names.
# Play well with other scripts by avoiding global function and variable names.
# 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.
# "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.

==Namespaces==
Unobtrusive JavaScript should add as little as possible to the global [[Object (computer science)|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 (programming language)|Java]] language.<ref>{{cite book |last=Flanagan |first=David |title=JavaScript: The Definitive Guide |edition=5th |year=2006 |publisher=O'Reilly & Associates |isbn=0-596-10199-6 |chapter=10}}</ref>
<syntaxhighlight lang="javascript">
var org = org || {};
if (typeof org !== 'object') {
throw new Error("org already defined as non-object");
}

org.example = org.example || {};
if (typeof org.example !== 'object') {
throw new Error("org.example already defined as non-object");
}
</syntaxhighlight>
While variables, functions and objects of all kinds can be further defined within such namespace objects, it is usually recommended to use [[Closure (computer programming)|closures]] within the namespace to further [[Information hiding|isolate]] what will become [[Class (computer science)#Information hiding and encapsulation|private]] variables and functions, as well as to export what will be the public [[Interface (computing)|interface]] of each module of functionality. The code above could be followed directly by the following, which uses an [[Immediately invoked function expression|IIFE]] to establish its closure:<ref name="Heilmann"/>
<syntaxhighlight lang="javascript">
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 of closure
</syntaxhighlight>

From any other module, these public methods could be invoked in either way as follows
<syntaxhighlight lang="javascript">
org.example.Highlight.goBlue();

var h = org.example.Highlight;
h.goGreen();
</syntaxhighlight>

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.

==Degrading gracefully==
{{main|Progressive enhancement}}

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 JavaScript Framework|Prototype]] can simplify this process and help ensure that individual browser and browser version implementation details are [[Abstraction (computer science)|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.<ref name="Flanagan2006"/>

This requirement is a basic tenet of [[web accessibility]], 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.<ref>{{cite web|title=Equality Act 2010|url=http://www.legislation.gov.uk/ukpga/2010/15/contents|publisher=Her Majesty’s Stationery Office|access-date=7 September 2011}}</ref> While a lot of effort may be put into designing and implementing a slick [[client-side]] 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]] functionality that will be available without the use of JavaScript at all.

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

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

This will work as it is without JavaScript. Unobtrusive JavaScript, in this case, during page-load, could find all the <code>a</code> elements that have a class of <code>manual-link</code> and remove them from the page DOM. It could then find all the images of class <code>thumb</code> and attach an <code>onmouseover</code> or an <code>onclick</code> event handler that is specified in-line to provide the slick behaviour. For example, when invoked the event handler may send an Ajax request to the server for the full-size image, then add a <code>div</code> to the page DOM invoking existing [[CSS]] so it appears in front of existing content, which itself may become partially greyed out. The <code>div</code> 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 <code>div</code> 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, its advocates generally have subscribed to a number of related principles, such as:


The broader definitions of unobtrusive JavaScript have much in common with general programming best practices, such as [[Information hiding|encapsulation]] and [[abstraction layer]]s, avoidance of [[global variable]]s, meaningful [[naming conventions (programming)|naming conventions]], use of appropriate [[design patterns]], and systematic [[software testing|testing]].<ref>{{cite book |last=White |first=Alexei |date=2009 |chapter=Unobtrusive JavaScript |title=JavaScript Programmer's Reference |series=Wrox Programmer to Programmer |location=Chichester, UK; Hoboken, NJ |publisher=Wiley |page=[https://books.google.com/books?id=XJrXl71TITIC&pg=PA311 311] |isbn=9780470344729 |oclc=421783941}}</ref>
* Standard compliance, i.e. adherence to the [[World Wide Web Consortium|W3C]] [[Document Object Model|DOM]] and event model, and avoidance of browser-specific extensions.
* [[Progressive enhancement|Capability detection]], i.e. testing for specific functionality before it is used.<ref>{{cite web|url=http://dev.opera.com/articles/view/using-capability-detection/|title=Dev.Opera — Using Capability Detection|access-date=19 October 2016}}</ref> 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 [[Information hiding|encapsulation]] and [[abstraction layer]]s, avoidance of [[global variable]]s, meaningful [[naming conventions (programming)|naming conventions]], use of appropriate [[design patterns]], and systematic [[software testing|testing]].


==See also==
==See also==
* [[Graceful degradation]]
* [[Standards compliance]]
* [[Progressive enhancement]]


==References==
==References==
{{Reflist}}


==Further reading==
{{Reflist|30em}}
{{Refbegin}}
* {{cite journal |last=Amery |first=Luke |date=March 2009 |title=Unobtrusive JavaScript Explained |journal=[[APC (magazine)|APC]] |publisher=[[Bauer Media Group]] |volume=29 |issue=3 |page=89}}
* {{cite book |last1=Brinzarea-Iamandi |first1=Bogdan |last2=Hendix |first2=Audra |last3=Darie |first3=Cristian |date=2009 |chapter=Unobtrusive JavaScript |title=AJAX and PHP: Building Modern Web Applications |edition=2nd |location=Birmingham, UK |publisher=[[Packt Publishing]] |pages=205–206 |isbn=9781847197726 |oclc=607690639}}
* {{cite book |last=Johansen |first=Christian |date=2011 |chapter=Unobtrusive JavaScript |title=Test-driven JavaScript Development |series=Developer's Library Series |location=Upper Saddle River, NJ |publisher=[[Addison-Wesley]] |pages=177–196 |isbn=9780321683915 |oclc=613420202}}
* {{cite book |last=Kyrnin |first=Jennifer |date=2015 |chapter=Unobtrusive JavaScript |title=Sams Teach Yourself Responsive Web Design in 24 Hours |series=Sams Teach Yourself in 24 Hours |location=Indianapolis, IN |publisher=Sams |pages=[https://books.google.com/books?id=1pCKBQAAQBAJ&pg=PA95 95–101] |isbn=9780672338380 |oclc=872430002}}
* {{cite book |last=Skinner |first=Jesse |date=2007 |title=Unobtrusive Ajax |series=O'Reilly Short Cuts |location=Sebastopol, CA |publisher=[[O'Reilly Media]] |isbn=9780596510244 |oclc=172622153}}
* {{cite book |last=Smith |first=Peter |date=2013 |chapter=Unobtrusive JavaScript |title=Professional Website Performance: Optimizing the Front-end and Back-end |location=Indianapolis, IN |publisher=Wiley |pages=120 |isbn=9781118487525 |oclc=809561237}}
* {{cite web |title=The Principles of Unobtrusive JavaScript |website=www.w3.org |publisher=[[W3C]] Web Standards Curriculum |url=https://www.w3.org/wiki/The_principles_of_unobtrusive_JavaScript |date=2011 |access-date=2021-07-05}}
* {{cite book |last=Vora |first=Pawan |date=2009 |chapter=Unobtrusive JavaScript |title=Web Application Design Patterns |location=Amsterdam; London |publisher=[[Morgan Kaufmann Publishers]] |pages=[https://archive.org/details/webapplicationde0000vora/page/347 347–349] |isbn=9780123742650 |oclc=255902089 |chapter-url=https://archive.org/details/webapplicationde0000vora/page/347 |chapter-url-access=registration}}
{{Refend}}


{{JavaScript}}
{{JavaScript}}

Revision as of 02:52, 5 July 2021

Unobtrusive JavaScript is a general approach to the use of client-side JavaScript in web pages so that if JavaScript features are partially or fully absent in a user's web browser, then the user notices as little as possible any lack of the web page's JavaScript functionality.[1] The term has been used by different technical writers to emphasize different aspects of front-end web development. For some writers, the term has been understood more generally to refer to separation of functionality (the "behavior layer") from a web page's structure/content and presentation,[2] while other writers have used the term more precisely to refer to the use of progressive enhancement to support user agents that lack certain JavaScript functionality and users that have disabled JavaScript.[3] Following the latter definition, unobtrusive JavaScript contributes to web accessibility insofar as it helps ensure that that all users—whatever their computing platform—get roughly equal access to all of the web page's information and functionality.[4][5]

Overview

A typical client-side dynamic web page can be conceived as consisting of four parts: the marked-up content (HTML), the style sheet (CSS), client-side JavaScript, and embedded objects such as images.[6]: 5  The client-side JavaScript part can be conceived as enhancing the other parts by adding features or functionality that would not be possible without JavaScript.[6]: 3 

The concept of "unobtrusiveness" in relation to client-side JavaScript was coined in 2002 by Stuart Langridge[7] in the article "Unobtrusive DHTML, and the power of unordered lists".[8] In the article Langridge argued for a way to keep all JavaScript code, including event handlers, outside of the HTML when using dynamic HTML (DHTML).[7] He said that the the purpose of this kind of organization of code was "providing a better user experience for people whose browsers can support it, and not affecting those whose browsers cannot", while also making scripting easier for web developers.[7] Langridge later expanded upon this thought and emphasized that the core meaning of "unobtrusive" is that "if a given Web browser doesn't support the DHTML features you're using, that absence should affect the user experience as little as possible".[1] In other words, for Langridge, "unobtrusive" principally refers to users' experience of the absence of JavaScript features in a given situation.[1]

Variant definitions

Other authors have described variations on the essential elements of unobtrusiveness.

David Flanagan's book JavaScript: The Definitive Guide (2006) said that while there is no specific formula, there are three main goals of unobtrusive JavaScript:[4]

  • To separate JavaScript from HTML markup, as well as keeping modules of JavaScript independent of other modules using basic conventions such as the use of namespaces to prevent namespace collisions and the use of module initialization code;
  • To degrade gracefully—all content should be available without all or any of the JavaScript running successfully;
  • To not impede the accessibility of the HTML, and ideally to improve it, whether the user has personal disabilities or are using an unusual, or unusually configured, browser.

The Web Standards Project, in its JavaScript Manifesto (2006), said that the "purpose of JavaScript is enhancing the usability of web pages by adding interaction to them", and described four benefits of unobtrusive DOM scripting:[9]

  1. Usability: An unobtrusive DOM script does not draw the attention of the user—"visitors just 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, some of which were wider in scope than other narrower definitions of "unobtrusive":[10]

  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 browsers fail, what assumptions users 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.

The broader definitions of unobtrusive JavaScript have much in common with general programming best practices, such as encapsulation and abstraction layers, avoidance of global variables, meaningful naming conventions, use of appropriate design patterns, and systematic testing.[11]

See also

References

  1. ^ a b c Langridge, Stuart (2005). DHTML Utopia: Modern Web Design Using JavaScript & DOM. Collingwood, VIC, Australia: SitePoint. p. 75. ISBN 9780957921894. OCLC 60690615. An important design constraint when adding DHTML to your Websites is that it should be unobtrusive. By 'unobtrusive,' I mean that if a given Web browser doesn't support the DHTML features you're using, that absence should affect the user experience as little as possible. Errors should not be shown to the user: the site should be perfectly usable without the DHTML enhancements. (Reference to the first edition, since it shows how the author pioneered the concept.) The same passage is in an article excerpted from the book: Langridge, Stuart (2005-06-01). "DHTML Utopia: Modern Web Design Using JavaScript & DOM". articles.sitepoint.com. Archived from the original on 2010-04-21. Retrieved 2016-10-18.
  2. ^ Keith, Jeremy (2006-06-20). "Behavioral Separation". www.alistapart.com. Retrieved 2007-01-27. Separating out behavior from markup like this is called unobtrusive JavaScript.
  3. ^ Olsson, Tommy (2007-02-06). "Graceful Degradation & Progressive Enhancement". accessites.org. Archived from the original on 2017-07-18. Retrieved 2009-01-03. Progressive enhancement when it comes to JavaScript is becoming more common these days. The key to this is known as unobtrusive JavaScript. An unobtrusive script is silently ignored by user agents that do not support it, but is applied by more capable devices. Just like an external style sheet. {{cite web}}: |archive-date= / |archive-url= timestamp mismatch; 2017-05-17 suggested (help)
  4. ^ a b Flanagan, David (2006). "Unobtrusive JavaScript". JavaScript: The Definitive Guide (5th ed.). O'Reilly Media. p. 241–242. ISBN 9780596101992. OCLC 64313259.
  5. ^ Connor, Joshue O. (2012). "Unobtrusive JavaScript". Pro HTML5 Accessibility: Building an Inclusive Web. Berkeley, CA: Apress. pp. 71. doi:10.1007/978-1-4302-4195-9_3. ISBN 9781430241942. OCLC 757486357.
  6. ^ a b Goodman, Danny; Morrison, Michael; Novitski, Paul; Rayl, Tia Gustaff (2010). "JavaScript's Role in the World Wide Web and Beyond". JavaScript Bible (7th ed.). Indianapolis, IN: Wiley. pp. 3–13. ISBN 9780470526910. OCLC 435731997.
  7. ^ a b c "Building dynamic websites". www.netmag.co.uk. 2006-08-09. Archived from the original on 2010-12-05. Retrieved 2010-05-18.
  8. ^ Langridge, Stuart (November 2002). "Unobtrusive DHTML, and the power of unordered lists". www.kryogenix.org. Archived from the original on 2002-12-04. Retrieved 2008-08-07.
  9. ^ "The JavaScript Manifesto". www.webstandards.org. Web Standards Project. Archived from the original on 2006-06-14. Retrieved 8 Feb 2011.
  10. ^ Heilmann, Christian (2007). "The seven rules of Unobtrusive JavaScript". icant.co.uk. Archived from the original on 2 May 2011. Retrieved 8 February 2011. See also: Heilmann, Christian (2006). "Unobtrusive JavaScript". In Thatcher, Jim; Burks, Michael R.; Heilmann, Christian; Henry, Shawn Lawton; Kirkpatrick, Andrew; Lauke, Patrick H.; Lawson, Bruce; Regan, Bob; Rutter, Richard; Urban, Mark (eds.). Web Accessibility: Web Standards And Regulatory Compliance. Berkeley, CA: Friends of Ed; distributed by Springer-Verlag. pp. 301–331. doi:10.1007/978-1-4302-0188-5_10. ISBN 1590596382.
  11. ^ White, Alexei (2009). "Unobtrusive JavaScript". JavaScript Programmer's Reference. Wrox Programmer to Programmer. Chichester, UK; Hoboken, NJ: Wiley. p. 311. ISBN 9780470344729. OCLC 421783941.

Further reading