To improve jQuery's performance, you need to do seven things well, and jquery should do seven things well.

Source: Internet
Author: User

To improve jQuery's performance, you need to do seven things well, and jquery should do seven things well.

Do seven things to help you improve jQuery's performance. Do you want to know which things?

1. Append Outside of Loops

Anything that involves DOM has a price. If you attach a large number of elements to the DOM, you will want to append them all at once, instead of multiple times. When an element is attached to a loop, a common problem occurs.

$.each( myArray, function( i, item ) {  var newListItem = "<li>" + item + "</li>";  $( "#ballers" ).append( newListItem ); });

A common technique is to use document fragment ). In each iteration of a loop, elements are appended to fragments rather than DOM elements. After the loop ends, add the fragment to the DOM element.

var frag = document.createDocumentFragment();$.each( myArray, function( i, item ) {  var newListItem = document.createElement( "li" );  var itemText = document.createTextNode( item );  newListItem.appendChild( itemText );  frag.appendChild( newListItem );});$( "#ballers" )[ 0 ].appendChild( frag );

Another simple technique is to build a string continuously in each iteration of a loop. After the loop ends, set the HTML of the DOM element to this string.

var myHtml = "";$.each( myArray, function( i, item ) {  myHtml += "<li>" + item + "</li>";});$( "#ballers" ).html( myHtml );

Of course there are other tips for you to try. A site named jsperf provides a good way to test these performances. This website allows you to use every Benchmark Test Technique and visualize its cross-platform performance test results.

2. Cache Length During Loops

In the for loop, do not access the length attribute of the array every time; cache it in advance.

var myLength = myArray.length;for ( var i = 0; i < myLength; i++ ) {  // do stuff}

3. Detach Elements to Work with Them

DOM operations are slow, so you want to minimize alignment. JQuery 1.4 introduced a method named detach () to help solve this problem. It allows you to separate elements from the DOM when operating on them.

var $table = $( "#myTable" );var $parent = $table.parent();$table.detach();// ... add lots and lots of rows to table$parent.append( $table );

4. Don't Act on Absent Elements

If you are planning to run a large amount of code on an empty selector, jQuery will not give any prompt-it will continue to execute, as if there were no errors. You must verify the number of elements contained in the selector.

// Bad: This runs three functions before it// realizes there's nothing in the selection$( "#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 Guide applies to jQuery UI components that require a large amount of overhead when the selector does not contain elements.

5. Optimize Selectors

Compared with the past, selector optimization is not so important because many browsers implement the document. querySelectorAll () method and jQuery transfers the selector burden to the browser. But there are still some skills to remember.

ID-based Selector

Starting with an ID as a selector is always the best.

// Fast: $( "#container div.robotarm" );  // Super-fast: $( "#container" ).find( "div.robotarm" );

Use. the find () method will be faster, because the first selector has been processed, without having to use the noisy selector engine -- ID-Only selector that has used document. the getElementById () method is fast because it is the native method of the browser.

Specificity

Describe the right of the selector in detail as much as possible, and the opposite should be done on the left.

// Unoptimized:$( "div.data .gonzalez" ); // Optimized: $( ".data td.gonzalez" );

Try to describe the selector in the form of tag. class on the far right of the selector, and try to use only tag or. class on the left.

Avoid overuse of specificity

 $( ".data table.attendees td.gonzalez" );  // Better: Drop the middle if possible. $( ".data td.gonzalez" );

To please "DOM" is always helpful to improve the selector performance, because the selector engine does not need to perform too much traversal when searching for elements.

Avoid using a universal Selector

If a selector explicitly or implicitly matches within an uncertain range, the performance will be greatly affected.

$ (". Buttons> * "); // Extremely expensive. $ (". buttons "). children (); // Much better. $ (". category: radio "); // Implied universal selection. $ (". category *: radio "); // Same thing, explicit now. $ (". category input: radio "); // Much better. copy Code 6. use Stylesheets for Changing CSS on 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 by nearly 60%.

// Fine for up to 20 elements, slow after that:$( "a.swedberg" ).css( "color", "#0769ad" );// Much faster:$( "<style type=\"text/css\">a.swedberg { color: #0769ad }</style>")  .appendTo( "head" );

7. Don't Treat jQuery as a Black Box

The above are seven things that need to be done well to improve jQuery's performance!

Articles you may be interested in:
  • JQuery Tips (4) Some Tips for improving JQuery Performance
  • Jquery Optimization Efficiency Improvement performance Solution
  • Summary of jquery best practices for improving performance
  • Jquery-based high-performance switching between td and input and modifiable content implementation code
  • Create a jQuery-based high-performance TreeView (asp.net)
  • How does the JQuery each () function optimize the performance of the circular DOM structure?
  • Introduction to selection and use of jquery Selector
  • Javascript compression and jquery compression (improving page loading performance/protecting labor results)
  • Performance Comparison Between JQuery for and each

Related Article

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.