jQuery Optimization on the Site

Programming

Nowadays, almost all websites use jQuery to play animation and perform a many of a Java Script programming language and is easy to use. But, when a website’s functionality is very large and complex, users browser may not be so smooth and optimized. That’s why I have decided to write this article. Below you will find a list of very simple rules that help JQuery work much better while fully optimized.

1. To search for element you should search by ID

$('#someId'), because for this jQuery uses an internal function javascript getElementById().

Secondly, for speed, search by name $('tagName'), which also uses internal function javascript getElementsByTagName(). The other variants are less high-speed. For example take the following code:

<div id="content"> 
<form method="post" action="/"> 
   <h2>Choose the color</h2>
    <ul id="color_light">     
<li><input type="radio" class="on" name="light" value="red" />Red</li>   
   <li><input type="radio" class="off" name="light" value="yellow" />Yellow</li>   
   <li><input type="radio" class="off" name="light" value="green" />Green</li> </ul>  
  <input class="button" id="color_button" type="submit" value="Go"/>
   </form>
</div>

Let’s display the search of these elements

$ ('#color_button') - will be performed maximum speed;
$ ('#content .button') - will be performed slowly;
$ ('.button:first') - will be performed more slowly.

2. For a quick search of group elements, it is better to point to the nearest common relative that has an identifier:

$('#content input') - it will be more effective than simply $('input').

3. To quick search element by class, it is better to specify tags names:

$('input .button'). It will search faster, than $('.button'). In the first case, jQuery at first must find all input all elements and then among them it will look for elements with a button class. In the second case, it will conduct exhaustive searches of all page elements for quick elements search by class.

4. You shouldn’t conduct a search for the same items over and over again.

It is quite and exhaustive procedure, even if you use fastest selector.
$ ('# myElement'). bind ('click', function () {...});
$ ('# myElement'). css ('border', '3 px dashed yellow ');
$ ('# myElement'). fadeIn ('slow');

It is better to use code in this way:

Var myElement = $('#myElement');
myElement.bind('click', function () {...});
myElement.css('border', '3 px dashed yellow ');
myElement.fadeIn ('slow');

jQuery will search every element with the ID of my element, so it will be more much wiser to find the element one time and save it and then use for it needed operations.

This is just some of my rules. The next 4 rules you will find in my new blog. Stay tuned!

See also: Custom checkboxes and radio buttons, using CSS (without Java scripts)

Comments