Best Practices for JavaScript Development with jQuery

Table of Contents

Symbols

Name inline functions   mozilla style

Required blocks

http://jslint.com/lint.html This is a jslint recommendation to enclose

Documentation

Framework (jQuery)

Files

Deliver as .js files   files crockford

Do not embed in HTML   files crockford

JavaScript in element attributes   progressive

When working with jQuery there is generally a preferred layout to keep pages readable.

http://icant.co.uk/articles/seven-rules-of-unobtrusive-javascript/

http://cookiecrook.com/AIR/2003/train/jsguidelines.php

Load scripts late   files crockford performance

Late in the body as possible

Naming conventions

Filename prefix of extensions: jquery

Variable in loop: i, j, k

Grammar

Indentation: 4 spaces   style crockford

Audit: untabify.

Line Length: 80 characters   style crockford

Split chain at dot: true   style resig

Comments: //   style crockford

Required blocks: true   jslint

if (condition) { statements; }

Operators

Don't coerce values: true   style jslint

Objects

Variable Declarations   crockford

Function Declarations   crockford rashbrook

rashbrook: Name inline functions This might not be a best practice, doesn't appear to be used: observe: function offlineObserve(aSubject, aTopic, aState)

Names   crockford

Disallow leading _ in identifiers

Statements   crockford

Don't pollute the global namespace

This should be moved into separate sections:

Play well with others (Namespacing, scope and patterns) in http://icant.co.uk/articles/seven-rules-of-unobtrusive-javascript/

This would cover the use of body onload activities, global values, etc.

http://developer.apple.com/documentation/ScriptingAutomation/Conceptual/JSCodingGuide/Advanced/Advanced.html#//apple_ref/doc/uid/TP40006541-SW1

recommends:

Use the var keyword. Any variable created without the var keyword is created at the global scope and is never eligible for garbage collection, presenting the opportunity for a memory leak.

Use a global array, global object, or namespace prefix. If you need global variables, use a global object that contains all of the global variables, like this

Newlines follow anonymous functions with jQuery   style

Split any method calls that invoke anonymous foundtions. This should be done to reduce the amount of extra whitespace but makes the scripts longer

jQuery variables   style

If a jQuery object is returned should a "$" prefix be used?

http://dotnetslackers.com/articles/ajax/JQuery-Primer-Part-1.aspx

This isn't recommended since it violates ECMA 262 guidelines.

Disallow = and !   jslint

Cache function pointers   performance

For iterating through DOM elements initialize the variable:

styles = getElementsByClassName("script); for (var i = 0; i < styles.length; i++) { console.log(styles[i]); }

http://blogs.msdn.com/ie/archive/2006/08/28/728654.aspx

Avoid Using the ‘with’ Keyword   style

Author: Jason Walsh

j@wal.sh

Last Updated: 2024-10-30 16:43:54