What are the best practices to improve jQuery selector performance?

jQueryWeb DevelopmentFront End Technology

To enhance the performance of jQuery selector, you need to perform optimization. Here are some of the techniques:

Cache Selector

Caching enhances the performance of the application. Cache your jQuery selectors for better performance. This can be done using the ID as your selector. For example, this caches the selector and stores it in variable.

var $elm = $("#elm");

Instead of using the jQuery ID selector, use the $elm variable:

var $elm = $("#elm");
$elm.addClass(‘example’);

Use ID selector

jQuery is a JavaScript library. In JavaScript, document.getElementById() is used to select the HTML element, which is the fastest way. Since jQuery is written on top of JavaScript, it calls the JavaScript functions to complete the task. Using ID as a selector in jQuery, calls the document.getElementById(), so always try to use the ID selector.

Avoid repeating selectors

Do not repeat your selector and use chaining, to chain multiple methods in a single call. Let’s say the following is the code:

Here’s the optimized version:

$("div").css({"color", "blue", "font-size", "12px"}).text("This is demo text.”);
raja
Published on 15-Dec-2017 20:22:17
Advertisements