Chapter 9. Performance Best Practices
Prev Part III. Advanced Topics Next

Chapter 9. Performance Best Practices

Table of Contents

Cache length during loops
Append new content outside of a loop
Keep things DRY
Beware anonymous functions
Optimize Selectors
Use Event Delegation
Detach Elements to Work With Them
Use Stylesheets for Changing CSS on Many Elements
Use $.data Instead of $.fn.data
Don't Act on Absent Elements
Variable Definition
Conditionals
Don't Treat jQuery as a Black Box

This chapter covers a number of jQuery and JavaScript best practices, in no particular order. Many of the best practices in this chapter are based on the jQuery Anti-Patterns for Performance presentation by Paul Irish.

Cache length during loops

In a for loop, don't access the length property of an array every time; cache it beforehand.

var myLength = myArray.length;

for (var i = 0; i < myLength; i++) {
    // do stuff
}

Copyright Rebecca Murphey, released under the Creative Commons Attribution-Share Alike 3.0 United States license.


Prev Up Next
This Section is a Work in Progress Home Append new content outside of a loop