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'.
});
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。