提高jQuery效率
来源:互联网 发布:windows http服务器 编辑:程序博客网 时间:2024/06/07 15:23
1.缓存变量
DOM遍历是昂贵的,所以尽量将会重用的元素缓存。- // 糟糕
- h = $('#element').height();
- $('#element').css('height',h-20);
- // 建议
- $element = $('#element');
- h = $element.height();
- $element.css('height',h-20);
2.使用匈牙利命名法
在变量前加$前缀,便于识别出jQuery对象。- // 糟糕
- var first = $('#first');
- var second = $('#second');
- var value = $first.val();
- // 建议 - 在jQuery对象前加$前缀
- var $first = $('#first');
- var $second = $('#second'),
- var value = $first.val();
- 3.请使用’On’
- 在新版jQuery中,更短的 on(“click”) 用来取代类似 click() 这样的函数。在之前的版本中 on() 就是 bind()。自从jQuery 1.7版本后,on() 附加事件处理程序的首选方法。然而,出于一致性考虑,你可以简单的全部使用 on()方法。
- // 糟糕
- $first.click(function(){
- $first.css('border','1px solid red');
- $first.css('color','blue');
- });
- $first.hover(function(){
- $first.css('border','1px solid red');
- })
- // 建议
- $first.on('click',function(){
- $first.css('border','1px solid red');
- $first.css('color','blue');
- })
- $first.on('hover',function(){
- $first.css('border','1px solid red');
- })
- 4.维持代码的可读性
伴随着精简代码和使用链式的同时,可能带来代码的难以阅读。添加缩紧和换行能起到很好的效果。- // 糟糕
- $second.html(value);
- $second.on('click',function(){
- alert('hello everybody');
- }).fadeIn('slow').animate({height:'120px'},500);
- // 建议
- $second.html(value);
- $second
- .on('click',function(){ alert('hello everybody');})
- .fadeIn('slow')
- .animate({height:'120px'},500);
5.熟记技巧
你可能对使用jQuery中的方法缺少经验,一定要查看的文档,可能会有一个更好或更快的方法来使用它。- // 糟糕
- $('#id').data(key,value);
- // 建议 (高效)
- $.data('#id',key,value);
6.使用子查询缓存的父元素
正如前面所提到的,DOM遍历是一项昂贵的操作。典型做法是缓存父元素并在选择子元素时重用这些缓存元素。- // 糟糕
- var
- $container = $('#container'),
- $containerLi = $('#container li'),
- $containerLiSpan = $('#container li span');
- // 建议 (高效)
- var
- $container = $('#container '),
- $containerLi = $container.find('li'),
- $containerLiSpan= $containerLi.find('span');
0 0