javascript 性能優化

1. 儘可能減小和DOM對象和瀏覽器對象的交互。

2. 選擇元素的時候儘可能經過ID選擇器去選取元素document.getElement('id');

3. 避免每次使用browser objects 方法時都遍歷原型。能夠用一個變量存放這些方法。以下:

var slice = [].slice,
    split = "".split;

4.簡化你的html,使你的html更加簡潔,刪除那些沒必要要的div,span 等標籤。這能提升javascript的dom操做的速度,從而提升性能。以下:yahoo34條中的一條,減小dom元素。

Reduce the Number of DOM Elements. A complex page means more bytes to download and it also means slower DOM access in JavaScript. It makes a difference if you loop through 500 or 5000 DOM elements on the page when you want to add an event handler for example.javascript

document.getElementsByTagName('*').length獲取頁面中dom元素的數量。

5.對dom的操做批量進行,對樣式的更改最後經過增長和刪除類來進行。由於每次dom操做和元素的樣式更改瀏覽器都會從新渲染,對性能形成影響。

var ul = document.getElementById('id'),
    fragment = document.createDocumentFragment(),
    data = ['text1','text2','text3'],
    li;
for(var i = 0,len = data.length; i < len; i++) {
    li = document.createElment('li');
    li.appendChild(document.createTextNode(data[i]));
    fragment.appendChild(li);
}
ul.appendChild(fragment);

6. 減小對js庫的依賴

7. 合併js壓縮js

8. 僅僅加載你須要的模塊,可使用依賴管理如Require.js

9. 在IE上使用Array.prototype.join()來代替字符串相加的方法來鏈接字符串。

Joining strings using the plus sign (ie var ab = 'a' + 'b';) creates performance issues in IE when used within an iteration. This is because, like Java and C#, JavaScript uses unmutable strings. Basically, when you concatenate two strings, a third string is constructed for gathering the results with its own object instantiation logic and memory allocation. While other browsers have various compilation tricks around this, IE is particularly bad at it.html

10.充分利用引用類型,對於函數傳參來講,傳引用與傳基本類型的值來講,引用的開銷更小。

11.縮短做用域鏈

12.利用好this變量,經過使用call,apply

var Person = Object.create({
  init: function(name) {
     this.name = name;
  },
  do: function(callback) {
     callback.apply(this);
  }
});
var john = new Person('john');
john.do(function() {
    alert(this.name); // 'john' gets alerted because we rewired 'this'.
});

13. 使用switch代替if/else 語句。switch語句在編譯的時候更容易被優化。

14. 變量聲明帶上var 慎用全局變量

15. 慎用閉包,閉包若是造成循環引用的話。會致使內存泄漏。

16. 使用for 代替 for in 遍歷數組

相關文章
相關標籤/搜索