- 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’)