-Our standard for writing jQuery.
- Type checks
- Chaining
- Plugins
- Efficient selectors
- Absent elements
- Caching in loops
- Ajax
- Abstracting functions
-
Checking for the type of object using jQuery should be consistent. Additional type checks are available using JavaScript.
// Function jQuery.isFunction(object) // Array jQuery.isArray(object)
-
Chaining should be used when calling consecutive methods on the same object and each chain should be written on a new line for consistency. The chain should be indented one level.
// bad var nomensa = $('.nomensa'); nomensa.addClass('foo'); nomensa.show(); // good var nomensa = $('.nomensa'); nomensa .addClass('foo') .show();
-
Plugins should not create global variables. This excludes third party libraries.
// bad var plugin = 'nomensa'; (function ($, window, document, undefined) { // ...stuff... }); // good (function ($, window, document, undefined) { var plugin = 'nomensa'; // ...stuff... });
-
Be specific with selectors to reduce the use of the Sizzle engine in jQuery.
// bad $('.nomensa ul li a'); // good $('.nomensa a'); // better var nomensa = $('.nomensa'); nomensa.find('a');
-
Wildcard or Universal selectors can be slow to match. Avoid using them.
// bad $('.nomensa > *'); $('.nomensa > :radio'); $('.nomensa > *:radio'); // good $('.nomensa').children(); $('.nomensa input:radio');
-
Prevent code from executing if the object being manipulated does not exist.
// bad var nomensa = $('nomensa'); nomensa.hide(); // good var nomensa = $('nomensa'); if (nomensa.length !== 0) { nomensa.hide(); }
-
Properties used in conditions for loops should be cached beforehand.
// bad var links = $('.nomensa a'); for (var i = 0; i < links.length; i++) { // ...stuff... } // good var linksCount = $('.nomensa a').length; for (var i = 0; i < linksCount; i++) { // ...stuff... }
-
Use the 'ajax' method instead of 'get', 'getJSON' and 'post'. The 'ajax' method can be used for all requests.
// bad $.get('path/to/file.html', callback()); // good $.ajax({ type: 'GET', url: 'path/to/file.html' });
- Functions used within jQuery methods should be abstracted into one place. There can be two advantages from this:
-
It encourages functions to be re-used without the burden of refactoring them;
-
Improves readability;
-
Easier to debug and maintain code.
// bad var link = $('.link'), button = $('.button'); link.click(function() { // ...stuff... }); button.click(function() { // ...the same stuff... });