Jul 3, 2007

Unobtrusive DOM Scripting

Everything that you’ve learned up to this point comes to one incredibly important goal: writing your JavaScript so that it interacts with your users unobtrusively and naturally. The driving force behind this style of scripting is that you can now focus your energy on writing good code that will work in modern browsers while failing gracefully for older (unsupported) browsers.To achieve this, you could combine three techniques that you’ve learned to make an application unobtrusively scripted:

  1. All functionality in your application should be verified. For example, if you wish to access the HTML DOM you need to verify that it exists and has all the functions that you need to use it (e.g., if ( document && document.getElementById ) ). This technique is discussed in Chapter 2.
  2. Use the DOM to quickly and uniformly access elements in your document. Since you already know that the browser supports DOM functions, you can feel free to write your code simply and without hacks or kludges.
  3. Finally, you dynamically bind all events to the document using the DOM and your addEvent function. Nowhere must you have something such as this: . This is very bad in the eyes of coding unobtrusively, as that code will effectively do nothing if JavaScript is turned off or if the user has an old version of a browser that you don’t support. Since you’re just pointing the user to a nonsensical URL, it will give no interaction to users who are unable to support your scripting functionality.

If it isn’t apparent already, you need to pretend that the user does not have JavaScript installed at all, or that his browser may be inferior in some way. Go ahead, open your browser, visit your favorite web page, and turn off JavaScript; does it still work? How about all CSS; can you still navigate to where you need to go? Finally, is it possible to use your site without a mouse? All of these should be part of the ultimate goal for your web site. Thankfully, since you’ve built up an excellent understanding of how to code really efficient JavaScript code, the cost of this transition is negligible and can be done with minimal effort.