Writing good, effective JavaScript relies on four core principles:
Graceful degradation
If JavaScript is turned off, or fails to run, the user should still be able to access the site. (This is the same rule for CSS and images). The user may not experience all the bells and whistles you would wish them too, but the basic functionality of the site should remain unchanged. Features that are heavily dependent on JavaScript should not be vital to one’s use of the site.
Progressive enhancement
JavaScript is used to enhance content that is already present, not create new content.
Keep data, appearance and behaviour separate
Returning to our original table for the uses of web technology and adding to it:
HTML | CSS | JavaScript |
---|---|---|
content | appearance | behaviour (client-side) |
“what something is” | “how something looks” | “how something acts on the page” |
semantic markup of data | rules for appearance of content | rules for the behaviour of content |
Mixing the roles of these technologies leads to frustration and confusion.
Don't use JavaScript when CSS will do
Most web developers believe you have to use JavaScript to make an image gallery. You don’t. Most web developers believe that you must use JavaScript to create a drop-down menu. You don’t.
JavaScript still very much has its place and role: but with solid support for CSS Levels 1 and 2 in all modern browsers, you don't need it for many of the effects that people think the technology must be used to create. This becomes increasingly true with CSS3 and HTML5, which have support for animation. CSS is, generally speaking, faster, lighter, and easier to code and maintain than JavaScript.
Photograph by Massimo Valiani, used under a Creative Commons Attribution-NonCommercial 2.0 Generic license
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.