一、Append Outside of loops在循壞外添加
https://jsperf.com/性能測試test
1.bad
$.each( myArray, function( i, item ) {
var newListItem = "<li>" + item + "</li>";
$( "#ballers" ).append( newListItem );
});
2.good
1)使用document fragment
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 );
2)使用字符串追加
var myHtml = "";
$.each( myArray, function( i, item ) { myHtml += "<li>" + item + "</li>"; }); $( "#ballers" ).html( myHtml );二、Cache Length During Loops在循環前緩存長度
var myLength = myArray.length; for ( var i = 0; i < myLength; i++ ) { // do stuff }
三、Detach Elements to work with them
var table = $( "#myTable" );
var parent = table.parent();
table.detach();
// ... add lots and lots of rows to table
parent.append( table );
四、Don't Act on Absent Elements不要執行缺失的元素
// Bad: This runs three functions before it
// realizes there's nothing in the selection
$( "#nosuchthing" ).slideUp();
// Better:
var elem = $( "#nosuchthing" );
if ( elem.length ) {
elem.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/
});
五、Optimize Selectors優化選擇器
1.jQuery Extensions
// Slower (the zero-based :even selector is a jQuery extension)
$( "#my-table tr:even" );
// Better, though not exactly equivalent
$( "#my-table tr:nth-child(odd)" );
2.Avoid Excessive Specificity
$( ".data table.attendees td.gonzalez" );
// Better: Drop the middle if possible.
$( ".data td.gonzalez" );
3.ID-Based Selectors基於ID選擇器
// Fast:
$( "#container div.robotarm" );
// Super-fast:
$( "#container" ).find( "div.robotarm" );
4.Tips for Older Browsers
// Unoptimized:
$( "div.data .gonzalez" );
// Optimized:
$( ".data td.gonzalez" );
5.避免使用全選
$( ".buttons > *" ); // Extremely expensive.
$( ".buttons" ).children(); // Much better.
$( ":radio" ); // Implied universal selection.
$( "*:radio" ); // Same thing, explicit now.
$( "input:radio" ); // Much better.
六、Use Stylesheets for Changing CSS on Many Elements使用樣式表改變css
// Fine for up to 20 elements, slow after that:
$( "a.swedberg" ).css( "color", "#0769ad" );
// Much faster:超過20個元素的話,使用這個方法可能會提高60%的效率
$( "<style type=\"text/css\">a.swedberg { color: #0769ad }</style>")
.appendTo( "head" );
七、Don't Treat jQuery as a Black Box使用源碼
https://code.jquery.com/jquery/