Unobtrusive JavaScript
CSS allows the separation of content from presentation. Im the same way, JavaScript allows the separation of content from behavior. This is called unobtrusive JavaScript. Follow these guidelines:
- Avoid event handler attributes, for example:
<a href="#" onclick="..."> and <body onload="...">. Instead, attach events to the DOM from JavaScript.
- Prefer to use externally-linked scripts rather than inline scripts.
- Avoid having
<script> elements mixed throughout the content. Keep scripts confined to one place either in the <head> or the end of the <body>.
- Avoid using
document.write(). Instead, manipulate the DOM using standard DOM methods, or use the innerHTML property.
Progressive Enhancement
Progressive enhancement is a fundamental design paradigm that supersedes graceful degradation as a way of dealing with lack of cutting-edge JavaScript support in browsers.
With graceful degradation, the target platform is the modern, JavaScript-enabled desktop browser.
Strategies are then developed for dealing gracefully with older browsers, mobile devices, accessibility agents, or browsers with JavaScript disabled.
With progressive enhancement, the target platform is plain old semantic HTML (POSH) and HTTP, which are universally supported.
Strategies are then developed for adding interactivity to the page, if and when JavaScript is enabled.
This approach guarantees baseline functionality for a wide variety of browsers, accessibility agents, mobile phones, search-engine bots, etc.
JavaScript Progressive Enhancement Decision Tree »
Other Guidelines
- The reglib event delegation library is included on every standard page, feel free to take advantage of it.
- Avoid
<noscript>. This should be unnecessary with progressive enhancement.
- Avoid littering the global namespace with variables. This creates potential for conflict. If necessary, use closures to keep private data private.
- Avoid using
document.write(), especially in external scripts, since it halts page rendering until script is fully loaded and executed.
- Avoid manipulating style properties. Instead, alter the class and let CSS handle the presentation:
link.style.color="#c00"; // bad
addClassName(link, "warning"); // good
- Drop the
language attribute from all script tags. Use the type attribute instead:
<script language="JavaScript" src="foo.js"></script> <!-- bad -->
<script type="text/javascript" src="foo.js"></script> <!-- good -->
|