js代碼最佳化

來源:互聯網
上載者:User

標籤:change   asc   驗證   操作   seo   object   color   class   htm   

1、減少Jquery使用

處理dom遍曆和複雜的指令碼情境時,jquery可能有很大的協助,不過在處理簡單的、直截了當的代碼情境就會遲緩。儘可能的避免jquery對象建立,尤其在迴圈中。

2、最佳化迴圈

用被緩衝的數組長度

最佳化前for (var i = 0; i < arr.length; i++) {    // some code here}最佳化後for (var i = 0, len = arr.length; i < len; i++) {    // some code here}

3、if/else和swith語句

  • 如果只是1或者2個語句,那if/else效能更好點
  • 如果3個或者3個以上,那swith更好,這個可以通過測試來驗證(測試地址)

4、緩衝dom元素、jquey對象、對象/數組值

5、減少reflow

對dom的每次改變都會有一個重大的效能成本造成頁面reflow

  • 避免在document上直接進行頻繁的DOM操作,如果確實需要可以採用off-document的方式進行
  • 先將元素從document中刪除,完成修改後再把元素放回原來的位置
  • 將元素的display設定為”none”,完成修改後再把display修改為原來的值
  • 如果需要建立多個DOM節點,可以使用DocumentFragment建立完後一次性的加入
    //最佳化前var list=document.getElementById("list");for(var i=0;i<10;i++){var item=document.createElement("li");item.innerHTML="option "+(i+1);list.appendChild(item);}//最佳化後var list=document.getElementById("list");var fragment=document.createDocumentFragment();for(var i=0;i<10;i++){var item=document.createElement("li");item.innerHTML="option "+(i+1);fragment.appendChild(item);}list.appendChild(fragment);
  • 集中修改樣式
    最佳化前:function selectAnchor(element){ var changeDiv = document.getElementById(element);changeDiv.style.color = ‘#093′;changeDiv.style.background = ‘#fff’;changeDiv.style.height = ’100px’;} 最佳化後:CSS:changeDiv {background: #fff;color: #093;height: 100px;}JavaScript:function selectAnchor(element) {document.getElementById(element).className = ‘changeDiv’;}

     

6、避免全域的搜尋

var $button=$(".button");$buttons.find( "a.mybutton" );替代$( "a.mybutton" );

7、優先dom搜尋,然後再過濾

  • 優先使用原生的getElementById、getElementsByTagName
  • 例如.find( "a" ).filter( "[href=*‘url_fragment‘]" )替換.find( "a[href=*‘url_fragment‘]" 

8、綁定多個事件到一個元素

//最佳化前var $elem = $( "#element" );$elem.on( "mouseover", function( event ) {    // mouseover});$elem.on( "mouseout", function( event ) {    // mouseout});//最佳化後$( "#elem" ).on( "mouseover mouseout", function( event ) {    if ( event.type === "mouseover" ) {        // mouseover    } else {        // mouseout    }});

 9、Property深度

  • object.name<object.name.name
  • 這個property越深,擷取時間越長 

轉自:http://www.cnblogs.com/hj4444/p/3985321.html

js代碼最佳化

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.