- Use the latest jquery release
- Know your selectors (ID, element, class, pseudo & attribute)
- Use .find() -> $parent.find('.child').show() is the fastest than others (scoped selector)
- Don't use jQuery unless it's absolutely necessary -> this.id is fater than $(this).attr('id')
- Caching -> storing the result of a selection for later re-use, no repeat selection
- Chaining
- Event delegation -> if possible, use delegate instead of bind and live
- Each DOM insertion is costly -> keep the use of .append(), .insertBefore() and .insertAfter() to a minimum; .data() is better than .text() or .html(); $.data('#elem', key, value) is faster than $('elem').data(key, value)
- Avoid loops -> Javascript for or while loop is faster than jQuery .each()
- Avoid constructing new jQuery object unless ncessary -> use $.method() rather than $.fn.method(); $.text($text) is faster than $text.text(), $.data() is faster than $().data
In recent jQuery performance discussion, I summarized the following points based on different messages.
- Scope jquery selectors (use find)
- Know selectors performance => ID > element (tag) > class > pseudo & attribute
- Avoid loops => if loop is inevitable, consider for/while > $.each() if possible
- Cache the result of a selection for later use (using local variables if possible)
- DOM operation is expensive (esp. in a loop)
- Don't use $ unless it's necessary => this.name > $(this).attr('name’)
One more blog talking about jQuery performance http://www.artzstudio.com/2009/04/jquery-performance-rules/
ReplyDeleteAlways Descend From an #id
Use Tags Before Classes
Cache jQuery Objects
Harness the Power of Chaining
Use Sub-queries
Limit Direct DOM Manipulation
Leverage Event Delegation (a.k.a. Bubbling)
Eliminate Query Waste
Defer to $(window).load
Compress Your JS
Learn the Library
http://jquerysbestfriends.com
ReplyDeleteRequireJS
LABjs
YepNopeJS
Modernizr
Vapor.js
Templates: Microtemplates, Mustache, Haml, & jq-tmpl, Handlebars
Simple Inheritance
Underscore.js
PubSub
Prototypal YAY
EasyXDM
backbone.js
jquery UI
json2 and closure
FuncUnit
JavascriptMVC
JS Docs
http://jquery-howto.blogspot.com/2009/02/5-easy-tips-on-how-to-improve-code.html
ReplyDelete1. Use JavaScript native for() loop instead of jQuery's $.each() helper function
2. Do NOT append an element to the DOM in your loop.
3. If you have a lot of elements to be inserted into the DOM, surround them with a parent element for better performance.
4. Don't use string concatenation, instead use array's join() method for a very long strings
5. And the last but not least use setTimeout() function for your long list looping and concatenation functions.