您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

提升jQuery的性能需要做好七件事_jquery

2024/3/8 18:28:09发布17次查看
做好七件事帮你提升jquery的性能,想知道哪几件事情吗?
1. append outside of loops
凡是触及到dom都是有代价的。如果你向dom当中附加大量的元素,你会想一次性将它们全部附加进来,而不是分多次进行。当在循环当中附加元素就会产生一个常见的问题。
$.each( myarray, function( i, item ) { var newlistitem = + item + ; $( #ballers ).append( newlistitem ); });
一个常用的技巧是利用文档片段(document fragment)。在循环的每一次迭代当中,将元素附加到片段而不是dom元素当中。当循环结束后,将片段附加到dom元素当中即可。
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 );
另一个简单的技巧是在循环的每次迭代当中,持续构建一个字符串。当循环结束后,将dom元素的html设置成该字符串。
var myhtml = ;$.each( myarray, function( i, item ) { myhtml += + item + ;});$( #ballers ).html( myhtml );
当然还有其它一些技巧可以供你尝试。一个名为 jsperf 的站点为测试这些性能提供了一条好的出路。该网站允许你使用基准测试每一个技巧,并将其跨平台的性能测试结果可视化的展现出来。
2. cache length during loops
在for循环当中,不要每次都访问数组的 length 属性;应当事先将其缓存起来。
var mylength = myarray.length;for ( var i = 0; i * ); // extremely expensive.$( .buttons ).children(); // much better. $( .category :radio ); // implied universal selection.$( .category *:radio ); // same thing, explicit now.$( .category input:radio ); // much better.复制代码6. use stylesheets for changing css on many elements
假如你使用 .css() 方法来改变超过20个元素的css,应当考虑为页面添加一个样式标签作为替代,这样做可以提升将近60%的速度。
// fine for up to 20 elements, slow after that:$( a.swedberg ).css( color, #0769ad );// much faster:$( ) .appendto( head );
7. don't treat jquery as a black box
以上就是提升jquery的性能需要做好的七件事,清楚了吧!
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product