Top Tips for Optimizing Your jQuery Selectors
When your jQuery runs slow as a result of poorly organized or clunky code, it can really negatively affect your users’ experience. One easy way to optimize your jQuery and to help avoid slow-running code is to make sure that the selectors are constructed as well as they possibly can be. To make sure your selectors aren’t slowing down your code, apply the following tips to your jQuery:
1. When selecting elements, select by ID, not by class. Because of the native getElementById method, most browsers can select an element by ID much quicker than they can with a class, because using a class as a selector results in the jQuery having to move through the DOM.
2. If you are going to use a class as a selector, indicate the HTML tag type before the class name. The reason for this is similar to the reason for using elements rather than classes: there is a native getElementByTag method that makes it easier and quicker for the browser to find the class if it’s preceded by its HTML tag type.
3. Cache your elements as objects before you use them. If your browser only has to locate your selector once, it will make your code a lot quicker. To do this, you need to save an element as a variable in your jQuery that can be reused over and over. See below for an example:
var firstParagraph = $("#firstP)"; $firstParagraph.slideUp(); $firstParagraph.slideDown();