📜 ⬆️ ⬇️

JQuery effective usage rules

Here are a number of very simple rules, following which, your collaboration with jQuery will not be overshadowed by the rattle of a tensed browser. Of course, it is not often the case that the speed of javascript is critical, but it can still happen and happen at the most inappropriate moment. Therefore, it is better to keep these rules in your head and not to neglect them.

1. Effective element search

The fastest way is to search for items by identifier: $ ('# someId'), second in speed, is searching by tag name: $ ('tagName'). The high speed of their execution is due to the fact that their implementation uses the internal functions javascript: getElementById () and getElementsByTagName (). In this regard, there are several rules.

(For greater clarity, I will indicate the text of the page to which the JS code from the examples will be applied)
< div id ="content" >
< form method ="post" action ="/" >
< h2 > </ h2 >
< ul id ="color_light" >
< li >< input type ="radio" class ="on" name ="light" value ="red" /> </ li >
< li >< input type ="radio" class ="off" name ="light" value ="yellow" /> </ li >
< li >< input type ="radio" class ="off" name ="light" value ="green" /> </ li >
</ ul >
< input class ="button" id ="color_button" type ="submit" value ="Go" />
</ form >
</ div >

* This source code was highlighted with Source Code Highlighter .

1. If you are looking for one item, use the search by ID:
$('#color_button') - will be executed as quickly as possible
$('#content .button') - will be slower
$('.button:first') - even slower

2. If you are looking for a group of elements, specify the closest common relative with the identifier:
$('#content input') will be more efficient than just $('input') .

3. If you are looking for items by class, specify the tag name:
$('input.button') will search faster than $ ('. button'). In the first case, jQuery will first find all input elements, and among them it will search for elements with the button class. And in the second case, all elements of the page will be searched for this.

From all this, we can derive two basic rules:
1) To search for a single item, use id search: $('#someId')
2) When searching for a group of elements, try to stick to the following formula: $('#someId tagName.someClass')

And yet, do not try to improve the search by id using the following combinations:
$('#wrapId #someId')

This will only slow down the search.

2. Reuse item search result

You should not search for the same elements over and over again, this is quite an expensive procedure, even if you use the fastest selector:
$('#myElement').bind('click', function(){...});
. . .
$('#myElement').css('border', '3px dashed yellow');
. . .

In this case, jQuery will search for an element with the myElement identifier each time. It would be much more reasonable to find the element once, save it, and then apply the necessary operations to it:
var myElement = $('#myElement');
. . .
myElement.bind('click', function(){...});
. . .
myElement.css('border', '3px dashed yellow');
. . .

If the same elements are often used during the operation of your script, it will be reasonable to find these elements only once and save the result in a global variable:
function init()
elements = $('#someId tagName.someClass');

However, sometimes, it is necessary to make manipulations with different groups of elements, which, however, are related. For example, it can be form elements with which you need to perform many manipulations. In this case, we constantly have to look for the necessary elements:
$('#myForm input:checkbox') //
$('#myForm input:text') //
$('#myForm input:text[value != ""]') //
. . .

Instead, you can find all the elements of the form once, and if necessary, get out the necessary:
var inputs = $('#myForm input');
inputs.filter(':checkbox') //
inputs.filter(':text') //
inputs.filter(':text[value != ""]') //
. . .

Or, you may need to perform many manipulations with list items, including deleting and adding them. In this case, “caching” the list items will not be a good idea, since their composition will constantly change, and the “cache” will be irrelevant. However, you can save the list object itself in a global variable, which also significantly reduces computational costs:
myList = $('#myList');
. . .
myList.find('li:first').remove(); //
myList.find('li.showed').hide(); // showed

3. Avoid unnecessary manipulations with the DOM

The main idea here is that if you want to make a number of changes on the page (add / change elements), perform these manipulations locally and only after that make changes to the DOM. For example, if you want to add a hundred new elements to the list, it will be erroneous to do this elementwise:
var top_100_list = [...]; //
$mylist = $('#mylist'); //

for (var i=0; i< top_100_list.length; i++)
$mylist.append('<li>' + top_100_list[i] + '</li>');

it will be much more efficient to insert all the elements at once:
var top_100_list = [...]; //
var li_items = ""; // html-
$mylist = $('#mylist'); //

for (var i=0; i< top_100_list.length; i++)
li_items += '<li>' + top_100_list[i] + '</li>';

An even greater gain can be obtained if the group of inserted elements turns out to be “wrapped” by one element. Therefore, if we had the task to replace the contents of the list with hundreds of new elements, then the most optimal one would be this option:
var top_100_list = [...]; //
var new_ul = "<ul id='mylist'>"; // html-
$mylist = $('#mylist'); //

for (var i=0; i< top_100_list.length; i++)
new_ul += '<li>' + top_100_list[i] + '</li>';
new_ul += "</ul>";

Modifying elements locally will help the clone () method, which creates copies of elements, along with all their contents. Having made all the necessary changes with the copies, you can insert them back into the DOM, instead of the old versions (this can be done using the replaceWith () method).

4. Use event delegation

Sometimes, you have to install identical event handlers on a large group of elements. For example, you may need to set click handlers, list items. In such cases, instead of installing handlers for each list item, you can install one handler for the list itself. As is well known, standard javascript events that are triggered on an element are then called on all of its ancestors (the parent element, then the ancestor, etc.). Therefore, after the event occurs on a specific element of the list, it will be called on the object of the list itself. The event object that is passed to the handler, or rather, its event.target property, will help to understand who the event happened to. It always contains the DOM object of the original event source:
$(event.target).addClass('clicked'); // clicked

Source: https://habr.com/ru/post/103174/

All Articles