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.

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.

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 遍历数组

    原文作者:Refresh
    原文地址: https://segmentfault.com/a/1190000000459380
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞