apike.ca
Programming

CSS Practices for jQuery Performance

jQuery and CSS go together like peanut butter and jelly.
jQuery and CSS go together like peanut butter and jelly.

In this article, we're going to do some comparisons of jQuery performance to show how different ways of coding HTML and CSS can make a big difference. These tests are not meant as a browser comparison but to show that the results are consistent across them.

The first test is a comparison between a class and an id for getting a single page element.

Class Versus Id

The result of this first test is no surprise. A clear winner in all browsers is using an id selector. An id is guaranteed to be unique to the page and there is a JavaScript API call to get the dom element with an id. If you're going to need to look for something unique on the page and it's easy to give it an id then do so.

On the other hand, using ids in CSS is a bad idea. It makes it too hard to share style rules and have more than one of something on the page. So, classes are the way to go in CSS.

BrowserjQuery(".class")jQuery("#id")
FireFox389 ms177 ms
Safari159 ms44 ms
Chrome96 ms19 ms

Notes:

  • The test looped a 10,000 times.
  • The class occurred 1 time.

Class Versus Qualified Class

Next, we look at what to do with classes inside a container. We need a class to make the text bold. We could call the class "bold" but this might conflict with another class. So, being a thoughtful designer, we try to link the class to the container.

There's two ways to do it. We could add a CSS rule like ".container-bold" or "#container .bold" (use parent id or class the container has to narrow the class). The first option may look like it would be slower as the browser needs to look at the whole page. Also, instead of a nice and simple class name within the container, we're tacking on a lot of extra text. The CSS rule could even end up like: ".right-upper-side-article-list-bold". Good grief.

BrowserjQuery(".class")jQuery("#id .class")
FireFox1276 ms8174 ms
Safari3713 ms4417 ms
Chrome2722 ms3043 ms

Notes:

  • The test looped a 10,000 times.
  • The class occurred a 129 times.
  • Varying the total instances of the class seemed to linearly scale the results.

Well, that wordy class name is looking pretty good now. All browsers performed the direct class lookup faster. For FireFox, it's getting close to an order of magnitude slower to qualify using an id.

Quite simply, this shows that browsers have a fast way to grab all the elements in the dom with a certain class. Qualifying it with an id (or class) means jQuery probably needs to traverse the dom structure to find the elements that have the class.

Conclusion

In general, it's best to stick to simple selectors in jQuery if the selector will be called repeatedly. So, the CSS and HTML should accommodate this by having ids where they make sense and using unique css rules across the whole page.