jquery Enhanced Performance Best Practices summary _jquery

Source: Internet
Author: User

The jquery object is cached in the
In the For loop, do not access the length property of the array every time, we should first cache the object into a variable and then manipulate it, as follows:

Copy Code code as follows:

var mylength = myarray.length;
for (var i = 0; i < mylength; i++) {
Things to do
}

use append outside the loop

There is a cost to doing DOM operations, and if you need to add a large number of elements to the DOM, you should do it in batches, not one at a time.
Copy Code code 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 (), there will be multiple traversal lookup DOM elements, very inefficient document.createdocumentfragment ( To reduce the number of changes to the DOM structure of the page, and the number of refreshes

Or so
var myhtml = ';
$.each (myarray, function (I, item) {
html + + ' <li> ' + item + ' </li> ';
});
$ (' #ballers '). HTML (myhtml);

Keep your style simple
Copy Code code 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 ();
}
})

using anonymous functions with caution
Constraints on anonymous functions There is a pain everywhere. They are difficult to debug, maintain, test or reuse. Instead, we can use object encapsulation to organize those processing and callback functions and to manage them by name.
Copy Code code as follows:

Don't 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 given ID always use #id to find element
Copy Code code as follows:

Very fast
$ (' #container div.robotarm ');
Super fast
$ (' #container '). Find (' div.robotarm '); use $. The Fn.find method is faster because the first selector is not required to be processed by the selector engine, and the fastest selector in jquery is the ID selector. Because it comes directly from the JavaScript getElementById () method, which is very fast because it is native to the browser. If you need to select multiple elements, this necessarily involves DOM traversal and looping, and in order to improve performance, it is recommended that you inherit from the most recent ID.

Specifies that the right part of the selector should be as specific as possible and that the left side does not need to be so specific.
Copy Code code as follows:

Not optimized
$ (' Div.data. Gonzalez ');
After optimization
$ ('. Data Td.gonzalez '); If you can, try to use Tag.class on the right side of the selector, and only tag on the left or only. class.

avoid excessive and specific
Copy Code code as follows:

$ ('. Data table.attendees Td.gonzalez ');
It would be better not to write the middle.
$ ('. Data Td.gonzalez '); The refreshing DOM structure also helps to improve the performance of the selector, and the selector engine can run a few floors to find the element.


avoid using a non-directional wildcard selector
Copy Code code as follows:

$ ('. Buttons > * '); Very slow
$ ('. Buttons '). Children (); Much faster.
$ ('. Gender:radio '); Non-directional search
$ ('. Gender *:radio '); Ditto
$ ('. Gender Input:radio '); It's so much better.

Using Event delegation

Event delegation allows you to bind an event handler for a container element (for example, an unordered table) without having to bind each element within the container (for example, a list item). jquery provides $.fn.live and $.fn.delegate. If possible, you should use $.fn.delegate instead of $.fn.live, because it eliminates the need for unnecessary selection and, in its explicit case (the context of the $.fn.live document), 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 having to rebind the event, because it already has.

Delegating multiple events by event delegation to reduce event redundancy
Copy Code code 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);

The best: $.fn.delegate
$ (' #myList '). Delegate (' Li.trigger ', ' click ', HANDLERFN);

removing elements from
Dom operations are slow, and you should try to avoid manipulating them. jquery introduced in version 1.4
$.fn.detach removes all matching elements from the DOM.
Copy Code code as follows:

var $table = $ (' #myTable ');
var $parent = table.parent ();
$table. Detach ();
// ... Add a large number of rows to a table
$parent. Append (table);

Detach () and. Remove (), except. Detach () holds all jquery data associated with the removed element. This is useful when you need to move an element and soon insert the element into the DOM.


when a large number of elements modify CSS, you should use the style sheet

If you're using $.FN.CSS to modify CSS for more than 20 elements, consider adding a style label so that you can increase the speed by 60.
Copy Code code as follows:

More than 20 obvious slow
$ (' A.swedberg '). CSS (' color ', ' #asd123 ');
$ (' <style type= ' text/css ' >a.swedberg {color: #asd123}</style> '). Appendto (' head ');

Using $.data instead of $.fn.data to apply $.data to a DOM element is 10 times times faster than $.fn.data directly calling the jquery selection result. Although, it is to be sure that you understand the difference between the DOM element and the jquery selection result.
Copy Code code as follows:

Common
$ (elem). Data (key, value);
10 times times faster.
$.data (Elem, key, value);


don't spend time on the blank selection results.

jquery will not tell you that if you want to run the code on an empty selection, it will continue to run as if there is nothing wrong with it. Affect performance.
Copy Code code as follows:

It was so bad that three methods were executed before realizing that it was empty.
$ (' #nosuchthing '). Slideup ();

Better
var $mySelection = $ (' #nosuchthing ');
if ($mySelection. length) {
Myselection.slideup ();
}

Best: 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 the jquery UI widget because it costs a lot even if the element of the operation is empty.



Defining variables
A variable can define a declaration rather than a few
Copy Code code as follows:

Old Fashioned.
var test = 1;
var test2 = function () {...
};
var test3 = test2 (test);

New
var test = 1,
Test2 = function () {...
},
Test3 = test2 (test); In an automatically executed function, the definition of a variable can be completely omitted. (Function (foo, bar) {...)
}) (1, 2);


Conditional judgment
Copy Code code as follows:

Old method
if (type = = ' Foo ' | | |-type = = ' Bar ') {...
}

Good way
if (/^ (Foo|bar) $/.test (type)) {...
}

Finding objects
if (({
Foo:1,
Bar:1
}) [Type]) {...
}

Author: Zengxiang exhibition
Source: Life-long Learning (http://www.cnblogs.com/zengxiangzhan/)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.