Do seven things to improve jQuery's performance

  • 2020-03-30 01:34:54
  • OfStack

1. Append Outside of Loops

Touching the DOM comes with a price. If you append a large number of elements to the DOM, you want to append them all at once, rather than multiple times. A common problem occurs when adding elements to a loop.


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

A common technique is to use document fragments. During each iteration of the loop, the element is attached to the fragment rather than the DOM element. When the loop is over, attach 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 trick is to continually build a string during each iteration of the loop. When the loop ends, set the HTML of the DOM element to that string.


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

There are other techniques you can try. A site called jsperf provides a good way to test these capabilities. The site allows you to use each technique of benchmarking and visualize the results of its cross-platform performance tests.

2. Cache Length During Loops

In the for loop, don't access the length property of the array every time; It should be cached in advance.


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

Detach Elements to Work with Them

DOM manipulation is slow, so you want to minimize alignment. JQuery introduced a method called detach () in version 1.4 to help with this, which allows you to separate elements from the DOM as you manipulate 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're going to run a lot of code on an empty selector, jQuery doesn't give you any hints -- it will continue to execute as if nothing went wrong. It is up to you to verify how many elements the selector contains.


// 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 is especially useful for jQuery UI widgets that require a lot of overhead when the selector contains no elements.

5. Optimize Selectors

Selector optimization compared with the past is not so important, because many browsers implement the document. The querySelectorAll () method and the jQuery selector shifted the burden of one browser. But there are some tricks to keep in mind.

ID based selector

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


 // Fast:
 $( "#container div.robotarm" );

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

The.find() method is faster because the first selector has been processed without having to go through the noisy selector engine -- the id-only selector has been processed using the document.getelementbyid () method, which is fast because it is the browser's native method.

specificity

Describe the right side of the selector in as much detail as possible, and the left side in reverse.


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

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

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

Avoid overusing specificity


 $( ".data table.attendees td.gonzalez" );

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

Pleasing the "DOM" always improves the performance of the selector, because the selector engine does not have to traverse much while searching for elements.

Avoid using generic selectors

If a selector explicitly or implicitly indicates that it can be matched in an uncertain range it can significantly affect performance.


 $( ".buttons > *" ); // Extremely expensive.
 $( ".buttons" ).children(); // Much better.

 $( ".category :radio" ); // Implied universal selection.
 $( ".category *:radio" ); // Same thing, explicit now.
 $( ".category input:radio" ); // Much better.
 Use Stylesheets for Changing CSS on Many Elements

If you use the.css() method to change the CSS for more than 20 elements, consider adding a style tag to the page instead, which can increase 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" );
 Don't Treat jQuery as a Black Box

The source of jQuery as a document, you can put it (http://bit.ly/jqsource) in your favorites, often refer to.


Related articles: