Tips to Write Better jQuery code

Here are few tips that will help you write better way to write jQuery code.

1. Always Descend From an #id
(The fastest selector in jQuery is the ID selector because jQuery uses the browser’s native method, getElementByID(), to retrieve the object, resulting in a very fast query.)
2. Give your Selectors a Context
(By default, when you use a selector such as $(‘.myDiv’) the whole of the DOM will be traversed, which depending on the page could be expensive.

The jQuery function takes a second parameter when performing a selection.

jQuery( expression, context )

By providing a context to the selector, you give it an element to start searching within so that it doesn’t have to traverse the whole of the DOM.)
3. Use Tags Before Classes
4. Cache jQuery Objects
(Never select elements multiple times inside a loop EVER! It’d be a speed-killer!)
5. Use Sub-queries
6. Limit Direct DOM Manipulation
7. Leverage Event Delegation (a.k.a. Bubbling)
8. Eliminate Query Waste
9. Defer to $(window).load
10. jQuery’s new event handler live() is a much faster alternative to click().
11. Use find() rather than context

12. Always Use the Latest Version
(jQuery is in constant development and improvement. John and his team are always researching new

13. ways to improve program performances.)
14. . Combine and Minify Your Scripts
(YUI compressor, an excellent tool jQuery officially reccomends to minify scripts.)
13. Use For Instead of Each (Native functions are always faster than any helper counterparts.)
14. Return ‘false’ to prevent default behaviour

Share this nice post:

One thought on “Tips to Write Better jQuery code

Comments are closed.