jQuery Complacency
by Matthew Crist Tuesday, February 28th, 2012
jQuery makes it easy to do things. So much so, that developers can become complacent and not strive to make things better and faster. Selecting elements, loops and calendar widgets are all easier for us to build with jQuery, but it is easier to ignore what the browser gives us for efficiencies to help improve client side performance.
As we move away from computers towards mobile devices, the knowledge that allows us to reduce size and increase speed becomes more important. The current generation of web developers includes many who don’t know JavaScript as a language, but are fluent in jQuery. This leads to sites which are slow, especially on mobile. We need to go beyond jQuery and become more fluent in the language that makes jQuery so much fun.
This idea started to resonate with me last year with a tweet from @dhh. It pointed out that in the .each() function of jQuery, we as developers were constantly have to reinitialize the jQuery object during each iteration of a loop. Within minutes, someone had derived a new function called .quickEach() which proved to be much more performant. This has been iterated over a few more times as well to generate the fastest possible loop for iterating over the jQuery object. This is not intended to be use for looping over arrays.
As I’ve been looking into client side performance more recently, I decided to bake up a simple example to examine using .each() for simple array for loops in JavaScript. The jQuery .each() function makes it easy to loop over arrays, but as the array gets larger, it’s inefficiency can lead to less responsive browsers as compared to native for loops.
After proving that the .each() function was again slower than other options, I wanted to take a look at another useful jQuery function: .css().
The .css() function in jQuery allows you to easily set CSS attributes on elements. The example that I baked up is based on a problem that I am currently working on in which I need to set the left property on a group of about 100 elements as a table scrolls. Initially, I started out using the .css() function as it was the fastest way to prove out what I was trying to accomplish.
Unfortunately, it was slower that I would prefer and would cause flickering on the screen during the scroll. What I found to be the fastest way to set a css property involved a native JavaScript while loop that looped over the jQuery object, and then natively set the CSS for each element using the style property of the element.
As developers we can’t be complacent in learning a framework without learning the underlying language. Doing so leads to less performant results which negatively impacts your users on any device.