zoukankan      html  css  js  c++  java
  • Jquery 代码性能改善

    从jquery官网看到的,简单翻译了一下,很常规的几个改善方法:

    1:  在循环之外添加 (Append Outside of Loops)

      比如代码1:

    代码1清单:

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

    由于DOM操作会带来开销,所以每次循环都操作DOM,性能会差。推荐用一个字符串缓存需要添加的HTML内容,循环之后进行Append。

    1  var str = [];
    2 $.each( myArray, function( i, item ) {
    3  
    4      str.push("<li>" + item + "</li>");
    5 
    6 });
    7  $( "#ballers" ).append( str.join('');

    2: 缓存循环的长度

    这个好像地球人都知道:

    1 var myLength = myArray.length;
    2  
    3 for ( var i = 0; i < myLength; i++ ) {
    4  
    5     // do stuff
    6  
    7 }

    当然并不是所有的时候都要缓存一下循环的长度。比如要循环删除DOM节点的子节点,因为长度在每次删除子节点后都会变化。所以经验不是简单拿来用哦。

    3: 使用detach方法  Detach Elements to Work with Them

       好吧,我承认到现在还不知道detach是干嘛的,先把官网的东西拿下来,明日继续研究detach吧。

    官网上这么说的:当想尽量少的操作某个DOM的时候,可以用detach方法:

    1 var table = $( "#myTable" );
    2 var parent = table.parent();
    3  
    4 table.detach();
    5  
    6 // ... 要添加超多的row到table上
    7  
    8 parent.append( table );

    4:不要在不存在的DOM元素上进行操作   Don’t Act on Absent Elements

        

     1 // Bad: This runs three functions before it
     2 // realizes there's nothing in the selection
     3 $( "#nosuchthing" ).slideUp();
     4  
     5 // Better:
     6 var elem = $( "#nosuchthing" );
     7  
     8 if ( elem.length ) {
     9  
    10     elem.slideUp();
    11  
    12 }

    貌似我们很少去操作不存在的DOM元素,不过官网很快说了,在使用JQuery UI Widget的时候,这个原则非常实用,因为即使这个选择器不包含任何元素,开销也是很大滴!

    4:优化选择器 Optimize Selectors

         这个其实简单点,就是尽量缩小选择器筛选的范围。ID选择器是最快的。

     5:当用改变众多元素样式的时候使用样式表而不是用css方法
    // 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" );
    

      

  • 相关阅读:
    121. Best Time to Buy and Sell Stock
    70. Climbing Stairs
    647. Palindromic Substrings
    609. Find Duplicate File in System
    583. Delete Operation for Two Strings
    556 Next Greater Element III
    553. Optimal Division
    539. Minimum Time Difference
    537. Complex Number Multiplication
    227. Basic Calculator II
  • 原文地址:https://www.cnblogs.com/xinchuang/p/3883768.html
Copyright © 2011-2022 走看看