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

相关文章
相关标签/搜索