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.
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.
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.
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.