jquery do seven things to help you improve the performance of jquery

Source: Internet
Author: User

1. Append Outside of Loops

Anything that touches the DOM comes at a price. If you attach a large number of elements to the DOM, you will want to attach them all at once, rather than doing them in multiple points. When attaching elements to a loop, a common problem arises.

1 $.each (MyArray, function (I, item) {2 3     var newlistitem = "<li>" + Item + "</li>"; 4 5     $ ("#ballers "). Append (Newlistitem); 6 7});

A common technique is to take advantage of document fragments (documents fragment). In each iteration of the loop, the element is appended to the fragment rather than the DOM element. When the loop is finished, append the fragment to the DOM element.

1 var frag = document.createdocumentfragment (); 2  3 $.each (MyArray, function (I, item) {4  5     var newlistitem = document.createelement ("Li"); 6     var ite MText = document.createTextNode (item);  7  8     newlistitem.appendchild (itemtext); 9     frag.appendchild (Newlistitem); $ ("#ballers") ) [0].appendchild (Frag);

Another simple trick is to keep building a string in each iteration of the loop. When the loop ends, the HTML of the DOM element is set to that string.

1 var myhtml = ""; 2 3 $.each (MyArray, function (I, item) {4 5     myhtml + = "<li>" + Item + "</li>"; 6 7}); 8 9 $ ("#ballers"). HTML (myhtml);

Of course there are some other tricks you can try. A site called Jsperf provides a good way to test these performance. The site allows you to use benchmarks to test every skill and visualize its cross-platform performance test results.

2. Cache Length During Loops

In the For loop, do not access the length property of the array every time, it should be cached beforehand.

1 var mylength = myarray.length;2 3 for (var i = 0; i < mylength; i++) {4 5     //do STUFF6 7}

3. Detach Elements to work with them

Manipulating the DOM is slow, so you want to minimize alignment. jquery introduced a method called Detach () in version 1.4 to help solve this problem, which allows you to isolate elements from the DOM as they are manipulated.

1 var $table = $ ("#myTable"), 2 var $parent = $table. Parent (); 3 4 $table. Detach (); 5 6//... add lots and lots of rows to Table7 8 $parent. Append ($table);

4. Don ' t Act on Absent Elements

If you are going to run a lot of code on an empty selector, jquery does not give any hint-it will continue to execute as if no error has occurred. It is up to you to verify how many elements the selector contains.

1//Bad:this runs three functions before it 2//realizes there ' s nothing in the selection 3 $ ("#nosuchthing"). Slideup (); 4  5//better:6 var $mySelection = $ ("#nosuchthing"), 7  8 if ($mySelection. length) {9     $mySelection. sl  Ideup ();}13//Best:add a doonce plugin.15 jQuery.fn.doOnce = function (func) {     this.length && Func.apply (this),     this;20 return}22 $ ("Li.cartitems"). Doonce (function () {?     //Make it ajax! \o/?26 27});

This guide is especially useful for jQuery UI widgets that require a lot of overhead when the selector does not contain elements.

5. Optimize Selectors

Selector optimization is not as important as it used to be, since many browsers implement the Document.queryselectorall () method and jquery shifts the burden of selectors to the browser. But there are still some tricks to keep in mind.

ID-based selectors

It is always best to start with an ID as a selector.

1//Fast:2 $ ("#container div.robotarm"); 3 4//Super-fast:5 $ ("#container"). Find ("Div.robotarm");

The way to use the. Find () method will be much faster because the first selector has been processed without the noisy selector engine-the id-only selector has been processed using the document.getElementById () method, which is fast, is because it is the native method of the browser.

Specificity

Describe the right side of the selector as detailed as possible, and on the left you should do the opposite.

1//Unoptimized:2 $ ("Div.data. Gonzalez"); 3 4//Optimized:5 $ (". Data Td.gonzalez");

Try to describe the selector at the far right of the selector using the Tag.class form, while on the left, use only the tag or. class.

Avoid excessive use of specificity

1 $ (". Data table.attendees Td.gonzalez"); 2 3//Better:drop the middle if possible.4 $ (". Data Td.gonzalez");

To curry favor with the DOM is always good for improving the performance of the selector because the selector engine does not have to traverse too much when searching for elements.

Avoid using universal selectors

If a selector explicitly or implies that it can match within an indeterminate range, it will greatly affect performance.

1 $ (". Buttons > *"); Extremely expensive.2 $ (". Buttons"). Children (); Much BETTER.3 4 $ (". Category:radio"); Implied Universal Selection.5 $ (". Category *:radio"); Same thing, explicit now.6 $ (". Category Input:radio"); Much better.

6. Use stylesheets to changing CSS on many Elements

If you use the. css () method to change the CSS of more than 20 elements, you should consider adding a style label to the page as an alternative, which can increase the speed of nearly 60%.

1//Fine for the elements, slow after that:2 $ ("A.swedberg"). CSS ("Color", "#0769ad"); 3 4//Much Faster:5 $ ("&L T;style type=\ "text/css\" >a.swedberg {color: #0769ad}</style> ") 6     . AppendTo (" Head ");

7. Don ' t Treat jQuery as a Black Box

The source of jquery as a document, you can save it (Http://bit.ly/jqsource) in your favorite folder, often consult reference.

jquery do seven things to help you improve the performance of jquery

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.