Writing Faster Selectors - J Query

Problem
Your code contains a large number of $('.classname') selectors. You’re caching them as described in the previous recipe, but the selectors are still affecting your page load time. You need to make them faster.

Solution

First, make sure you are using a recent version of jQuery (1.3.2 or later) for faster selector performance in most browsers, especially with class selectors.If you have control over the HTML page content, change the page to use id attributes and'#xyz' selectors instead of class attributes and '.xyz' selectors:

If you must use class name selectors, see whether there is a parent element that you can find with a faster ID selector, and then drill down from there to the child elements. For example, using the HTML from the previous recipe:

Discussion
It’s easy to forget that an innocent-looking call like $('.clientX') may take considerable time. Depending on the browser and version of jQuery, that selector may have to make a list of every DOM element in your page and loop through it looking for the specified class.
jQuery versions prior to 1.3 use this slow method in every browser. jQuery 1.3 introduced the Sizzle selector engine, which takes advantage of faster DOM APIs in newer browsers such as getElementsByClassName() and querySelectorAll().
However, for most websites you’ll probably need to support IE 7 for some time to come,and class selectors are slow in IE 7 when you have a complex page.
If you can use it, selecting by ID as in $('#myid') is generally very fast in all browsers,because it simply uses a single call to the getElementById() API.
It also helps to narrow down the number of elements that need to be searched, either by specifying a parent element, by making the class selector more specific with a tag name, or by combining those and other tricks.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics