Cache results from your jQuery selectors

A lot of developers use the popular jQuery JavaScript library, and the Sitefinity CMS team is not exception. We had quite a lot of code that relies on jQuery in Sitefinity CMS itself, and advise our customers to use it when writing extensions.

The biggest advantage of jQuery is its ability to easily select DOM elements using CSS-like selectors. We can write code to select by element ID or class, etc. Here is an example of how to select all elements with a given class name:

Sometimes, we need to perform operations on the result of a selection. Let's say we need to remove the highlight when an item is clicked and set another class. This is one way of doing it:

As you can see, we have used the same jQuery selector three times in the code above. As this functionality is abstracted by jQuery it is easy to write the code above and get done with this, as it works. However, developers should know that performing a selection in jQuery can be an expensive operation. Every time we invoke a selector, the browser performs a search through the DOM and returns a collection of the elements we want. This may take a while.

This is why, it is always recommended that we cache the results of our jQuery selections in a variable. The code above can be rewritten to save the selection and then use it to do what needs to be done.

Now we perform the selection only once and avoid the additional processing that is done of performing it. In case you are not adding or removing DOM elements, you should always cache the results of your jQuery selectors.

Additional information

Increase your Sitefinity skills by signing up for our free trainings. Get Sitefinity-certified at Progress Education Community to boost your credentials.

Web Security for Sitefinity Administrators

The free standalone Web Security lesson teaches administrators how to protect your websites and Sitefinity instance from external threats. Learn to configure HTTPS, SSL, allow lists for trusted sites, and cookie security, among others.

Foundations of Sitefinity ASP.NET Core Development

The free on-demand video course teaches developers how to use Sitefinity .NET Core and leverage its decoupled architecture and new way of coding against the platform.

Was this article helpful?