Edentity Web Systems
You solve creative. We crack code.
/Header/WhoWeAre.jpg
 

01/04/2010 jQuery and JavaScript Coding: Best Practices
Posted by Osvel Legon

When used correctly, jQuery can help you make your website more interactive, interesting and exciting.

Why jQuery?
The jQuery official web site states, "jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript". jQuery is simple to understand and easy to use, which means the learning curve is small, while the possibilities are (almost) infinite.

Javascript and Best Practices
Javascript has long been the subject of many heated debates about whether it is possible to use it while still adhering to best practices regarding accessibility and standards compliance.

The answer to this question is still unresolved, however, the emergence of Javascript frameworks like jQuery has provided the necessary tools to create beautiful websites without having to worry (as much) about accessibility issues.

Obviously there are cases where a Javascript solution is not the best option. The rule of thumb here is: use DOM scripting to enhance functionality, not create it.

Unobtrusive DOM Scripting
While the term “DOM scripting” really just refers to the use of scripts (in this case, Javascripts) to access the Document Object Model, it has widely become accepted as a way of describing what should really be called “unobtrusive DOM scripting”—basically, the art of adding Javascript to your page in such a way that if there were NO Javascript, the page would still work (or at least degrade gracefully). In the website world, our DOM scripting is done using Javascript.

The Bottom Line: Accessible, Degradable Content
The aim of any web producer, designer or developer is to create content that is accessible to the widest range of audience. However, this has to be carefully balanced with design, interactivity and beauty. Using the theories set out in this article, designers, developers and web producers will have the knowledge and understanding to use jQuery for DOM scripting in an accessible and degradable way; maintaining content that is beautiful, functional AND accessible.

Unobtrusive DOM Scripting?
In an ideal world, websites would have dynamic functionality AND effects that degrade well. What does this mean? It would mean finding a way to include, say, a snazzy Javascript Web 2.0 animated sliding news ticker widget in a web page, while still ensuring that it fails gracefully if a visitor’s browser can’t (or won’t) run Javascripts.

The theory behind this technique is quite simple: the ultimate aim is to use Javascript for non-invasive, “behavioural” elements of the page. Javascript is used to add or enhance interactivity and effects. The primary rules for DOM scripting follow.

Rule #1: Separate Javascript Functionality
Separate Javascript functionality into a “behavioural layer,” so that it is separate from and independent of (X)HTML and CSS. (X)HTML is the markup, CSS the presentation and Javascript the behavioural layer. This means storing ALL Javascript code in external script files and building pages that do not rely on Javascript to be usable.

Rule #2: NEVER Depend on Javascript
To be truly unobtrusive, a developer should never rely on Javascript support to deliver content or information. It’s fine to use Javascript to enhance the information, make it prettier, or more interactive—but never assume the user’s browser will have Javascript enabled. This rule of thumb can in fact be applied to any third-party technology, such as Flash or Java. If it’s not built into every web browser (and always enabled), then be sure that the page is still completely accessible and usable without it.

Rule #3: Semantic and Accessible Markup Comes First
It is very important that the (X)HTML markup is semantically structured. (While it is outside the scope of this article to explain why, see the links below for further reading on semantic markup.) The general rule here is that if the page’s markup is semantically structured, it should follow that it is also accessible to a wide range of devices. This is not always true, though, but it is a good rule of thumb to get one started.

Semantic markup is important to unobtrusive DOM scripting because it shapes the path the developer will take to create the DOM scripted effect. The FIRST step in building any jQuery-enhanced widget into a page is to write the markup and make sure that the markup is semantic. Once this is achieved, the developer can then use jQuery to interact with the semantically correct markup (leaving an (X)HTML document that is clean and readable, and separating the behavioural layer).

Understanding jQuery for Unobtrusive DOM Scripting
Understanding Selectors: the Backbone of jQuery - Performance Rules

Always Descend From an #id
The fastest selector in jQuery is the ID selector ($('#someid')). This is because it maps directly to a native JavaScript method, getElementById().

Selecting Multiple Elements
Once we start talking about selecting multiple elements, we are really talking about DOM traversal and looping, something that is slow. To minimize the performance hit, always descend from the closest parent ID.

Use Tags Before Classes
The second fastest selector in jQuery is the Tag selector ($('head')). Again, this is because it maps to a native JavaScript method, getElementsByTagName().

Note: The class selector is among the slowest selectors in jQuery; in IE it loops through the entire DOM. Avoid using it whenever possible. Never prefix an ID with a tag name.

Cache jQuery Objects
Get in the habit of saving your jQuery objects to a variable. First save the object to a local variable, and then continue your operations.

Harness the Power of Chaining
This allows us to write less code, making our JavaScript more lightweight.

Use Sub-queries
jQuery allows us to run additional selector operations on a wrapped set. This reduces performance overhead on subsequent selections since we already grabbed and stored the parent object in a local variable.

Limit Direct DOM Manipulation
The basic idea here is to create exactly what you need in memory, and then update the DOM. This is not a jQuery best practice, but a must for efficient JavaScript. Direct DOM manipulation is slow.

Leverage Event Delegation (a.k.a. Bubbling)
Unless told otherwise, every event (e.g. click, mouseover, etc.) in JavaScript “bubbles” up the DOM tree to parent elements. This is incredibly useful when we want many elements (nodes) to call the same function. Instead of binding an event listener function to many nodes—very inefficient—you can bind it once to their parent, and have it figure out which node triggered the event.

Eliminate Query Waste
Although jQuery fails nicely if it does not find any matching elements, it still takes time to look for them. If you have one global JavaScript for your entire site, it may be tempting to throw every one of your jQuery functions into $(document).ready(function(){ // all my glorious code }). Don’t you dare. Only run functions that are applicable to the page. The most efficient way to do this is to use inline initialization functions so your template has full control over when and where JavaScript executes.

Defer to $(window).load
There is a temptation among jQuery developers to hook everything into the $(document).ready pseudo event. After all, it is used in most examples you will find. Although $(document).ready is incredibly useful, it occurs during page render while objects are still downloading. If you notice your page stalling while loading, all those $(document).ready functions could be the reason why. You can reduce CPU utilization during the page load by binding your jQuery functions to the $(window).load event, which occurs after all objects called by the HTML (including <iframe> content) have downloaded.

Superfluous functionality such as drag and drop, binding visual effects and animations, pre-fetching hidden images, etc., are all good candidates for this technique.

Compress Your JS
Okay, this isn’t jQuery related, but I had to include it. There is a tendency to make JavaScript functions and variables overly descriptive, which is essential for developers but irrelevant to users. No more excuses, it’s time to build JS compression into our workflows.

Learn the Library
Print out this jQuery 1.3 cheat sheet, and make it a goal to eventually understand what each function does. 

Get ready.
$(document).ready()
Traditionally Javascript events were attached to a document using an “onload” attribute in the <body> tag of the page. Forget this practice. Wipe it from your mind.

jQuery provides us with a special utility on the document object, called “ready”, allowing us to execute code ONLY after the DOM has completely finished loading. This is the key to unobtrusive DOM scripting, as it allows us to completely separate our Javascript code from our markup. Using $(document).ready(), we can queue up a series of events and have them execute after the DOM is initialized.

This means that we can create entire effects for our pages without changing the markup for the elements in question.

Dynamic CSS Rule Creation
One problem with many DOM scripting effects is that they often require us to hide elements of the document from view. This hiding is usually achieved through CSS. However, this is less than desirable. If a user’s browser does not support Javascript (or has Javascript disabled), yet does support CSS, then the elements that we hide in CSS will never be visible, since our Javascript interactions will not have run.

The solution to this comes in the form of a plugin for jQuery called cssRule, which allows us to use Javascript to easily add CSS rules to the style sheet of the document. This means we can hide elements of the page using CSS—however the CSS is ONLY executed IF Javascript is running.

Further Reading
Further Reading: jQuery and JavaScript Practices
jQuery Web Site: How jQuery Works and Tutorials
John Resig + Other Contributors
One of jQuery’s true strengths is the documentation provided by John Resig and his team.
51 Best jQuery Tutorials and Examples
Easy As Pie: Unobtrusive JavaScript
Seven Rules of Unobtrusive JavaScript
Learning jQuery
Visual jQuery
jQuery Tutorials For Designers
jQuery For Designers
jQuery for Designers: learn how easy it is to apply web interaction using jQuery.
15 Days Of jQuery
jQuery tutorials and example code that takes you from zero to hero in no time flat.
15 Resources To Get You Started With jQuery From Scratch
The Seven Rules Of Pragmatic Progressive Enhancement
The Behaviour Layer Slides
Jeremy Keith
Great slide notes giving a quick rundown on unobtrusive Javascripting.
A List Apart: Behavioral Separation
Jeremy Keith
A more in-depth explanation of the idea of separating Javascript into an unobtrusive “behavioural” layer.
Unobtrusive JavaScript with jQuery
Simon Willison
A great set of slides about using jQuery unobtrusively. Also, finishes with a wonderful summary of jQuery methods and usage.
Further Reading: Semantic Markup
Wikipedia: Definition of Semantics
It’s worth understanding the idea of semantics in general prior to trying to wrap one’s head around the concept of semantic markup.
Who cares about semantic markup?
Dave Shea
Dave Shea explores the benefits of semantic markup and
Standards don’t necessarily have anything to do with being semantically correct
Jason Kottke
Kottke discusses the differences between standards compliance and semantic markup.
CSS3 selector specification
W3C
The complete specification for CSS3 selectors (most of which work perfectly in jQuery selectors also). This is great reading for anyone who likes to keep up to date with best practices and standards compliance.

Based on:
jQuery and JavaScript Coding: Examples and Best Practices - Smashing Magazine
jQuery Performance Rules - Best Practices for Speeding Up jQuery

 

« Back to Blog Main Page |

0 Comment(s)

Leave Comment

Name:
Comment:  
 
Edentity Web Systems Inc.
Suite 201
40 Spadina Ave.
Toronto ON
M5V 2H8
Tel:
416.591.2500
Fax:
416.352.5270

From Our Blog

02/09/2010
Amazon S3 – Now with Versioning! Posted by Joel Varty
02/02/2010
01/19/2010
411 Length Required in Firefox 3 Posted by Andre Small
Home | Who We Are | What We Do | Clients & Brands | Careers | Contact

Copyright © 2010 Edentity Web Systems Inc. Privacy Policy