JQuery code optimization method summary

Use a selection

in jQuery, you can select the same web page element with a variety of selectors. The performance of each selector is different, you should understand their performance difference

1, the fastest selector: ID selector and element tag selector

For example, The best statement performance:

$ (‘# id’) $ (‘Form’) $ (‘Input’)
   When encountering these selectors, jQuery will automatically call the native method of the browser (such as getElementByid ()), so their execution speed is fast. 
2, slower selector: Class selector
$ (‘. ClassName’) performance depends on different browsers. Firefox, Safari, Chrome, Opera browser, has native method getElementByClassName (), so speed is not slow. However, there is no deployment of IE5-IE8, so this selector will be quite slow in IE

3, the slowest selector: Pseudo selector and property selector

All hidden elements in the web page are used to use the pseudo selector:

$ (‘: hidden’)

 An example of the attribute selector is:   $ ('[attribute = value]') 

These two statements are the slowest because the browser does not have a native approach to them. However, some browser’s new version adds QuerySelector () and QuerySelectoryelectoralL () methods, so that the performance of such selectors will be greatly improved
Understand the father and child relationship
  The following six selectors are selected from the parent elements  

$ (‘. Child’, $ Parent) $ parent.find (‘. Child ‘) $ parent.children (‘. Child ‘) $ (‘ # parent> .child ‘) $ (‘ # parent .child ‘) $ (‘. Child ‘, $ (‘ # parent ‘))

1, the following statement means that a DOM object is given, then a child element is selected. JQuery will automatically turn this statement to $ .parent.find (‘Child’), which can cause a certain performance loss. It is more than 5% -10% higher than the fastest form

$ (‘. Child’, $ Parent)
2, this is the fastest statement. .find () method will call the native method of the browser (getElementById, getElementByname, getElementBytagname, etc.), so speed is faster

$ Parent.Find (‘. child’
   3, this statement is in JQuery, using $ .sibling () and JavaScript nextsibling () method, one traversal node. It is more slower than the fastest form 

   4, jQuery uses the Sizzle engine to handle various selectors. The selection order of the Sizzle engine is from right to left, so this statement is first selected .child, then oneA filtered parent element #parent, which results in slower than the fastest it forms about 70% 

$ ( ‘# parent> .child’)
   5, which is a statement of the same situation. However, the only one selected direct child elements, which can select a multi-level sub-element, so that it more slowly, about 77% slower 
than the fastest form

$ ( ‘# parent .child’)
   6, jQuery inside this statement will turn into $ ( '# parent'). find ( '. child '), slower than the fastest form of 23% 

$ (‘. child ‘, $ (‘ # parent ‘))
   Therefore, the best option is $ parent.find ( '. child'). Moreover, since the $ parent often has been generated in the previous operation, jQuery is cached, so further accelerate the execution speed 
However, the degree of use jQuery

jQuery go even faster, nor with the native compared javascript method. So there are occasions native methods you can use, try to avoid using jQuery.

In the simplest option as an example, document.getElementById ( “foo”) than $ ( “# foo”) 10 times faster
 Let's look at a typical example, a element binding function of a click event process:.   
$ ( ‘a’) click (function () {alert ($ (this) .attr ( ‘id’) );});

this code mean, clickingAfter the A element, the ID attribute of the element is popped up. In order to obtain this property, JQuery must be called twice in a row, and the first time is $ (this), the second time is Attr (‘ID’).

In fact, this treatment is completely unnecessary. More correct way of writing is to use JavaScript native approach, call this.id:

$ (‘a’). Click (function () {alert (this.id );});
 According to the test, this.id speed ratio is more than 20 times faster than $ 20.   Do a good job in cache 
Select a web page element and is the step of overhead. Therefore, the number of times using the selector should be, the better, and the selected result is as cached, which is easy to use later.
For example, the following is a bad way:

jQuery (‘# TOP’). Find (‘p.classa’); jQuery (‘#top’). Find (‘p.classb’);

A better way is:
   [ VAR CACHED = jQuery ('# TOP'); cached.find ('p.classa'); cached.find ('p.classb'); 

According to the test, the cache is more than 2-3 times

jQuery, it is to allow the use of chain write

$ (‘ Div ‘). Find (‘ h4 ‘). EQ (2) .html (‘ Hello ‘);
When using chainwriting, jQuery automatically caches the result of each step, so it is faster than non-chain. According to the test, the chain write ratio (without the use of cache) non-chain write, approximately 25%

Event entrustment

JavaScript event model, using “bubble” mode, also That is to say, the incident of child elements will be “bubble” step by step, and become an event of a parent element.
 Using this, it can greatly simplify the binding of the event. For example, there is a table (Table element), there is 100 lattice (TD elements), now requiring a click event (click) on each of the plaids. Do you need to execute the following command 100?   
$ (“TD”). On (“Click”, Function () {$ (this) .toggleclass (“click”);});

The answer is not required, we can bind this event on the Table element, because the TD element is clicked, this event will “bounce” to the parent element. TABLE, which is listened to

, therefore, this event only needs to be bound to the parent element 1 cope, without having to bind 100 times on the child element, thereby greatly improving performance. This is the “delegate process” of the event, that is, the child element “entrusted” parent element processing this event
  $ ("Table"). On ("click", "TD", Function () {$ (this) .ToggleClass ("Click");});  
Better way of writing, is bound to events Document object top

$ (document) .on (“Click”, “TD”, Function () {$ (this).ToggleClass (“Click”);});

If you want to cancel the incident binding, use OFF () method

$ (“Click”, “TD”);
   less modified DOM 
1, change the DOM structure The overhead is very large, so don’t use .Append () ,. INSERTBEFORE (), and .insetAfter ().

If you want to insert multiple elements, you will first merge them, and then insert it again. According to the test, the combined insertion is not combined and inserted, it will be nearly 10 times

2, if you want to perform a lot of DOM elements, you should use the .detach () method to take this element from the DOM. After the processing is completed, re-insert back the document. According to the test, use the .detach () method, 60% faster than not in use, fast 60%

3, if you want to store data on the DOM element, don’t write it below:
VAR ELEM = $ (‘# ELEM’); ELM.DATA (key, value);

to write
   VAR ELEM = $ ('# elem'); $. Data (ELEM [0], key, value); 

According to the test The latter write is approaching 10 times more written than the previous one. Because the ELEM.DATA () method is to define the prototype object on the jQuery function, and the $ .DATA () method is to call the jQuery function, the call is not called from complex jQuery objects, so the speed is much more fast
4, plugWhen entering HTML code, the browser nativeinTerHTML () method is faster than the jQuery object
  as little as possible to generate jQuery object  
whenever a selector (such as $ () ‘#id’)), generate a jQuery object. The jQuery object is a very large object with many properties and methods that will occupy a lot of resources. Therefore, try to generate jQuery object
for example, many jQuery methods have two versions, one is the version used by the jQuery object, and the other is the version used by the jQuery function. Below two examples, it is to take out a text of an element. Use the text () method

can be used either a version of the jQuery object:

VAR $ TEXT = $ (“# text”); var $ TS = $ text.text ();

can also be used for version of the jQuery function:

 VAR $ text = $ ("# text"); var $ ts = $ .text ($ text);   
Since the latter does not pass the jQuery object, the relative overhead is small, the speed is faster

Select the shortest method of the action domain chain
Strictly said, this One principle applies to all JavaScript programming, not only for jQuery
  We know that JavaScript variables use a chain scope. When reading a variable, you will find the variable in the current scope. If you can't find it, you will find the variable to the scope of the previous layer. Such a design makes reading a local variable than reading global variables  
Please see the following two codes, the first code is read global variables:

VAR A = 0; function x () {a + = 1;}

The second segment code is reading local variable :

Function Y () {var A = 0; A + = 1;}

Second section When the code reads the variable A, there is no need to travel to the previous layer, so it is more than five or six times higher than the first code
, when the object method is called, the Closure mode is more than prototype mode. Fast   

VAR x = function (name) {this.name = name;} x.prototype.get_name = function () { Return this.name;};

Closure mode:
VAR Y = function (name) {var y = {Name: Name}; Return {‘get_name’: function () {returno y.name;}};};
is also GET_NAME () method, Closure Faster mode

Using Pub / Sub Mode Management Event

When an event occurs, if you want to perform multiple operations continuously, it is best not to write to the following:

Function Dosomsomthing {DOSMETHINGELSE (); doonemorething ();}

To modify event triggers:
   function doomething {$ .Trigger ("do_something_done");} $ (document) .on ("do_something_done", function () {dosomethingelse ();}); 

Consider using Deferred object
   function dosomething () {var DFD = new $ .deferred (); // do something async, dam ... //dfd.resolve Return DFD.promise (); function dosomethingelse () {$ .when () {$ .when ()). Then (// the next thing);} 

© Copyright Notice
Just support it if you like
comment Grab the couch

Please log in to comment