IMPORTANT: This version of Sitefinity CMS is out of support and the respective product documentation is no longer maintained and can be outdated. Use the version selector to view a supported product version.
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.
Back To Top
To submit feedback, please update your cookie settings and allow the usage of Functional cookies.
Your feedback about this content is important