There are seven things you need to do to improve jQuery's performance

  • 2020-12-05 17:04:47
  • OfStack

7 things to do to improve jQuery's performance. Want to know what they are?

1. Append Outside of Loops

Everything that touches DOM comes at a price. If you add a lot of elements to DOM, you want to add them all at once, rather than multiple times. A common problem arises when attaching 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 (document fragment). During each iteration of the loop, the element is appended to the fragment instead of the DOM element. When the loop is finished, the fragment is appended 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 keep building a string for 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 );

Of course, there are 1 other tips you can try. A site called jsperf provides a good way to test these capabilities. The site allows you to benchmark each technique and visualize the results of cross-platform performance tests.

2. Cache Length During Loops

During the for loop, do not access the length attribute of the array every time; It should be cached beforehand.


var myLength = myArray.length;

for ( var i = 0; i < myLength; i++ ) {

  // do stuff

}

3. Detach Elements to Work with Them

Operating DOM is slow, so you want to operate with as little alignment as possible. jQuery introduced a method called detach() in version 1.4 to help solve this problem by allowing you to separate elements from 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 a hint -- it will continue executing 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 particularly useful for jQuery UI widgets that require significant overhead when the selector does not contain elements.

5. Optimize Selectors

Optimization of selectors is not as important as it used to be because many browsers implement the document.querySelectorAll () method and jQuery shifts the burden of selectors to the browser. But there are still a few tricks to keep in mind.

Selector based on ID

It is always best to start with an ID selector.


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

The.find () method is faster because the first selector is processed without going through the noisy selector engine - the selector of ES74en-ES75en is 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, but do the opposite for the left side.


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

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

Avoid overuse of specificity


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

Sucking up to "DOM" always improves the performance of selectors, because the selector engine doesn't have to do much traversal to search for elements.

Avoid generic selectors

If a selector explicitly or implicitly indicates that it can match within an uncertain range, 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 the code 
6. Use Stylesheets for Changing CSS on Many Elements

If you use the.css () method to change CSS with more than 20 elements, consider adding a style tag to the page instead, which can increase speed by nearly 60%.


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 );
0

7. Don't Treat jQuery as a Black Box

These are the seven things you need to do to improve the performance of the jQuery, clear!


Related articles: