Cache jQuery selectors for more efficient JavaScript

Having worked in collaborative and team contexts, I’ve had my fair share of situations where I’m working in amongst someone else’s code. There are plenty of things I could gab on about but one issue I commonly see is duplicate jQuery selectors.

Now, for really small scripts, duplicate selectors won’t cause you much heartache. However, it’s always wise to adopt good practices to prevent these habits from affecting your future work and saving you the potential scorn of some grumpy code reviewer.

What do duplicate jQuery selectors look like?

In the above example, we can see that the same selector string has been passed to jQuery twice. This effectively sends jQuery off to search the DOM for the same set of elements twice. This is unnecessary work for our old pal, jQuery, so let’s take a look at saving it some work.

How to cache those duplicate jQuery selectors.

Caching your jQuery selectors is as simple as saving them to a variable. Really, that’s it. Let’s take a look…

In the above example, we are doing exactly the same as the previous but we’re caching our selection to save jQuery from having to repeat itself.

Checking for the existence of matched elements for added benefit.

One additional little improvement I’ve thrown in is a check to see if the selection actually contains any items. If it doesn’t, there isn’t any point running any further code so our method exits early.

jQuery is incredibly easy and convenient and with just a few small tweaks we can ensure we keep our code as efficient as possible.

Need a website? Let's talk.

From website design & SEO through to custom WordPress plugin development. I transform ideas into dynamic, engaging, and high-performing solutions.
Subscribe to get the latest insights & updates in the world of web and how it impacts your business and website.
© 2024 Phil Kurth  |  All rights reserved.