您的位置:首页 > Web前端 > JQuery

【jQuery】jQuery官方基本教程的学习笔记6-性能Performance

2017-12-26 10:29 627 查看

一、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/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: