Coding Standards - jQuery Best Practices

JQuery
These articles will give you details on best practices for writing jQuery code.



1. Always use the latest version of the library from http://jquery.com


2. Know your selectors

All selectors are not equally efficient
a. ID selectors
b. Element selectors (form, input, etc.)
c. Class selectors
d. Pseudo and Attribute selectors (:visible, :hidden, [attribute=value], etc.)

3. DOM Insertion

Every DOM insertion is costly
You can minimize it by building HTML strings and using single append as late as possible
Use detach() if doing heavy interaction with a node then re-insert it when done

4. Caching

One of the most used features of jQuery is its ability to retrieve a DOM element by simply passing a reference to the $() function, be it an ID or class or whatever.
Every time we use $() function jQuery searches for the DOM element, and if the element is found it creates an object representing a clone of that element, with added capabilities.
This is true even for elements we already found using this function, so calling this function for the same elements more than once is redundant.

Bad


$("#foo").hide();
  $("#foo").css('color','red');
  $("#foo").show();

Good


var foo = $("#foo");
  foo.hide();
  foo.css('color', 'red');
  foo.show();



5. Chaining: Less code, easier to write and it runs faster

Good


  var foo = $("#foo");
  foo.hide().css('color','red').show();



6. Use ID selector whenever possible


7. Don't mix CSS with jQuery


8. Avoid multiple $(document).ready() calls


9. Do not refer jQuery file directly from internet. Better to download a file in local and provide path of local jQuery file

Written by Piece User : pooja@oneact.jp