Write more efficient, readable, and performant jQuery code

Performance is a BIG issue in applications that many developers pay no attention to. With the increasing speed of internet connections, performance issues become less and less apparent. However with mobile and tablet use, bandwidth issues and lower-processors can bring these issues to light and should help motivate developers to write better code.

jQuery is by far the most popular JavaScript library in the market and there are several things you can do to make your code faster and more efficient. In my previous blog post, I highlighted just two things you can do to your code to instantly make a difference. In this blog post, I will be highlighting things to make your every-day development more efficient and performant.

Naming variables

This one is simple, but will instantly make your code more readable. Any time you assign a variable that points to a jQuery object (selector, single jQuery element, or otherwise) you should prefix it with a $. This will help other developers instantly recognize that the variable is dealing with a jQuery object


Caching Selectors

jQuery makes it stupidly simple to grab elements on a page and perform operations. Because it is so easy, it also promotes inefficient code because it’s easy to forget basic principles, such as caching. If you are going to reuse elements from a selector, you should cache it in a variable.

Chaining

Chaining makes your code more efficient and less cluttered. If you are going to perform multiple operations on a jQuery object, chain the operations instead of breaking them into multiple statements.

How does chaining work? Most of jQuery’s functions actually return a pointer to the original object, or “this”. So $buttons.show() returns $(this), which makes the subsequent call to .css() on the original buttons object. I recommend using this as often as you can.

Master selector efficiency

If you master the art of selector efficiency, you can drastically improve the speed of your jQuery code. There are three basic principles:

  1. Use IDs instead of classes whenever possible
  2. Specificity – Be more specific on the right side of your selectors instead of at the beginning
  3. Avoid the universal selector (*)

For more details, see this helpful jQuery post.

Use multiple selectors for like operations

Do you ever want to perform the same operation on different selectors? You might write code like this:

Instead, you can write multiple selectors in one selector and make your code instantly more readable and efficient

Change CSS code with classes and not .css()

It’s tempting to use .css() function from jQuery to quickly change the css properties of an element. However, it is more efficient, readable, and maintainable to actually just write a css class instead.

With these small changes, you will make a huge impact on your application and other developers will thank you for it. Enjoy!