jQuery Optimization on the Site (Part 2)


In my JQuery work much better while fully optimized. But those rules are not enough, so, today I will share with you 4 more rules, which will help you.

1. Sometimes the same elements are used during the work of your script.

So, it will be easier for you to find these elements just one time and save it in Global variable. 

    function init()
    elements = $('#someId tagName.someClass');

2. Very often during your work, you have to manipulate with different elements group, which are related. 

For example, it may be form elements with which you should perform many different operations. In this case, you have to always find required elements.

$('#myForm input:checkbox') 
$('#myForm input:text')
$('#myForm input:text[value != ""]') 

It is wrong solution. Instead of this one you have to use this script, pointed below

var inputs = $('#myForm input'); 
inputs.filter(':text[value != ""]') 

3. Avoid unnecessary manipulations with DOM. 

If you want to add or change some elements on the page, you have to do this manipulation locally and just after this you may make changes to DOM. For example if you want to add 100 elements to the list it will be wrong to do it element by element.

var top_100_list = [...]; // content of new items 
$mylist = $('#mylist'); // necessary list
for (var i=0; i< top_100_list.length; i++)
$mylist.append(' <li>' + top_100_list[i] + '</li>');

It is better at first to generate all objects and then to add them to DOM:

var top_100_list = [...]; // content of new items 
var li_items = ""; //
$mylist = $('#mylist'); // necessary list
for (var i=0; i< top_100_list.length; i++)
li_items += ' <li>' + top_100_list[i] + '</li>';

4. Use the events delegation

Sometimes you should install the same event handlers for a big group of elements. For example, you may need to set handlers to the lists elements by clicking the mouse. In such cases, you may set one handler on the entire list instead of setting handlers on each element of the list. It is known, that standard javascipt elements called at any element, then would call at all his ancestors. That’s why after the event held on a particular list item, it will be called on the object of the list. Handler object event, especially its property event.target. will help you to understand where is the problem. It always contains the DOM-object of parental sources of events:


See also: jQuery optimization on the site