Cache jquery objects in
In a for loop, do not access the length attribute of the array every time. We should first cache the object into a variable and then operate it, as shown below:
Copy codeThe Code is as follows:
Var myLength = myArray. length;
For (var I = 0; I <myLength; I ++ ){
// What to do
}
Use append outside the loop
There is a price to perform DOM operations. If you need to add a large number of elements to the DOM, you should finish it in batches at a time, instead of at a time.
Copy codeThe Code is as follows:
// Don't do this
$. Each (reallyLongArray, function (count, item ){
Var newLI = '<li>' + item + '</li> ';
$ ('# Ballers'). append (newLI );
});
// Good practice
Var frag = document. createDocumentFragment ();
$. Each (reallyLongArray, function (count, item ){
Var newLI = '<li>' + item + '</li> ';
Frag. appendChild (newLI [0]);
});
$ ('# Ballers') [0]. appendChild (frag); do not use the $ ('# id') selector in each (). It will traverse the dom element multiple times to find the dom element, and the efficiency is very low. Use document. createDocumentFragment () to reduce the number of DOM structure changes and the number of refreshes on the page
// Or
Var myHtml = '';
$. Each (myArray, function (I, item ){
Html + = '<li>' + item + '</li> ';
});
('{Ballers'{.html (myHtml );
Maintain a concise style
Copy codeThe Code is as follows:
// Not ideal
If ($ ventfade. data ('currently ')! = 'Showing '){
$ Ventfade. stop ();
}
If ($ venthover. data ('currently ')! = 'Showing '){
$ Venthover. stop ();
}
If ($ spans. data ('currently ')! = 'Showing '){
$ Spans. stop ();
}
// Better
Var elems = [$ ventfade, $ venthover, $ spans];
$. Each (elems, function (k, v ){
If (v. data ('currently ')! = 'Showing '){
V. stop ();
}
})
Use anonymous functions with caution
The constraints on anonymous functions are everywhere painful. They are difficult to debug, maintain, test or reuse. Instead, we can use object encapsulation to organize and manage the processing and callback functions through naming.
Copy codeThe Code is as follows:
// Do not do this
$ (Document). ready (function (){...
$ ('# Magic'). click (function (e ){
$ ('# Yayeffects'). slideUp (function (){...
});
});
$ ('# Happiness'). load (url + '# unicorns', function (){...
})
});
// Better
Var PI = {
OnReady: function (){...
$ ('# Magic'). click (PI. candyMtn );
$ ('# Happiness'). load (url + '# unicorns', PI. unicornCb );
},
CandyMtn: function (e ){
$ ('# Yayeffects'). slideUp (PI. slideCb );
},
SlideCb: function (){...
},
UnicornCb: function (){...
}
}
$ (Document). ready (PI. onReady );
Optimization Selector
Node Selection and DOM operations, matching an element based on the given ID always uses # id to find the element
Copy codeThe Code is as follows:
// Very fast
$ ('# Container div. robotarm ');
// Super fast
$ ('# Iner '). find ('div. robotarm '); use $. fn. the find method is faster, because the first selector does not need to be processed by the selector engine. The fastest selector in jquery is the ID selector. because it is directly from the getElementById () method of Javascript, It is very fast because it is originating in the browser. If you need to select multiple elements, this will inevitably involve DOM traversal and loops. To improve performance, we recommend that you inherit from the latest ID.
The right part of the selector should be as specific as possible, and the left side should not be so specific.
Copy codeThe Code is as follows:
// Not optimized
$ ('Div. data. gonzarez ');
// After Optimization
$ ('. Data td. gonzarez'); if you can, use tag. class on the right side of the selector, and only tag or. class on the left side.
Avoid excessive specifics
Copy codeThe Code is as follows:
$ ('. Data table. attendees td. gonzarez ');
// It will be better if you do not write data in the middle
$ ('. Data td. gonzarez'); the refreshing DOM structure also helps improve the selector performance. The selector engine can run several layers to find that element.
Avoid using the untargeted wildcard Selector
Copy codeThe Code is as follows:
$ ('. Buttons> *'); // extremely slow
$ ('. Buttons'). children (); // much faster
$ ('. Gender: radio'); // no targeted search
$ ('. Gender *: radio'); // same as above
$ ('. Gender input: radio'); // This is much better
Use event Delegate
Event delegation allows you to bind an event handler to a container element (for example, an unordered list) without binding each element (for example, a list item) in the container. JQuery provides $. fn. live and $. fn. delegate. If possible, you should use $. fn. delegate instead of $. fn. live, because it saves unnecessary choices, it is clear (for $. fn. the context of the live file) reduces the overhead by about 80%. In addition to the benefits of performance improvement, event delegation also allows you to add new elements to the container without re-binding events, because there is already.
Bind multiple events at a time by event delegation to reduce event Redundancy
Copy codeThe Code is as follows:
// Bad (if there are many elements in the List)
$ ('Li. trigger'). click (handlerFn );
// Better: event delegation with $. fn. live
$ ('Li. trigger'). live ('click', handlerFn );
// Optimal: $. fn. delegate
$ ('# Mylist'). delegate ('Li. trigger', 'click', handlerFn );
Remove Element
DOM operations are slow. You should try to avoid them. JQuery introduced
$. Fn. detach removes all matching elements from the DOM.
Copy codeThe Code is as follows:
Var $ table = $ ('# mytable ');
Var $ parent = table. parent ();
$ Table. detach ();
//... Add a large number of rows to the table
$ Parent. append (table );
. Detach () is the same as. remove (), except that. detach () stores all jQuery data and is associated with the removed element. This method is useful when an element needs to be removed and soon inserted into the DOM.
When a large number of elements modify CSS, the style sheet should be used.
If you are using $.fn.css to modify CSS for more than 20 elements, consider adding a style label to improve the speed by 60%.
Copy codeThe Code is as follows:
// More than 20 obviously slow
Certificate ('a.swedberg'0000.css ('color', '# asd123 ');
$ ('<Style type = "text/css"> a. swedberg {color: # asd123} </style>'). appendTo ('head ');
Use $. data instead of $. fn. data will be $. apply data to DOM elements than directly call jQuery's selection result $. fn. data is 10 times faster. although, you must first determine the difference between the DOM element and the jQuery selection result.
Copy codeThe Code is as follows:
// Common
$ (Elem). data (key, value );
// Ten times faster
$. Data (elem, key, value );
Don't bother with the blank selection result
JQuery will not tell you that if the code you want to run is in an empty choice, it will continue to run, as if there is nothing wrong. Performance is affected.
Copy codeThe Code is as follows:
// It was too bad. After executing three methods, I realized that it was empty.
$ ('# Nosuchthing'). slideUp ();
// Better
Var $ mySelection = $ ('# nosuchthing ');
If ($ mySelection. length ){
MySelection. slideUp ();
}
// Optimal: add a doOnce plugin
JQuery. fn. doOnce = function (func ){
This. length & func. apply (this );
Return this;
}
$ ('Li. cartitems '). doOnce (function (){
// Make it ajax! \ O/
}); This layer of protection applies to jQuery UI widgets, because there are a lot of overhead even if the elements of the operation are empty.
Define Variables
Variables can define a declaration instead of several
Copy codeThe Code is as follows:
// Old Style
Var test = 1;
Var test2 = function (){...
};
Var test3 = test2 (test );
// New
Var test = 1,
Test2 = function (){...
},
Test3 = test2 (test); In the automatically executed function, the definition of variables can be completely saved. (Function (foo, bar ){...
}) (1, 2 );
Condition judgment
Copy codeThe Code is as follows:
// Old method
If (type = 'foo' | type = 'bar '){...
}
// Good method
If (/^ (foo | bar) $/. test (type )){...
}
// Search for objects
If (({
Foo: 1,
Bar: 1
}) [Type]) {...
}
Author: Zeng xiangzhan
Source: endless Learning (http://www.cnblogs.com/zengxiangzhan)