博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
编写更好的jQuery代码
阅读量:5259 次
发布时间:2019-06-14

本文共 6047 字,大约阅读时间需要 20 分钟。

有很多讨论jQuery和javascript性能的文章。然而,在这篇文章中,我计划总结一系列提供速度的建议来提高你的jQuery和javascript代码。当你准备用jQuery时,我强烈推荐遵循下面的规则:

1. 建立变量缓存(var caching)

DOM的遍历是相当费时间的,因此当你选择的元素计划重用他们时,一定要为他们建立缓存。

// bad codeh = $('#element').height();$('#element').css('height',h-20);// good code$element = $('#element');h = $element.height();$element.css('height',h-20);

2. 避免全局变量(avoid globals)

运用jQuery,和运用一般的javascript一样,最好确保你的变量在你的函数中拥有合适的范围。

// bad code$element = $('#element');h = $element.height();$element.css('height',h-20);// good codevar $element = $('#element');var h = $element.height();$element.css('height',h-20);

3. 应用匈牙利命名法(using hungarian notation)

在变量的前面放置$符号使人很容易确认这个变量包含一个jQuery对象。

// badvar first = $('#first');var second = $('#second');var value = $first.val();// better - we use to put $ symbol before jQuery-manipulated objectsvar $first = $('#first');var $second = $('#second'),var value = $first.val();

4. 应用变量链(use var chaining)(单变量模式)

Rather than having multiple var statements, you can combine them into a single statement. I suggest placing any variables without assigned values at the end.

var   $first = $('#first'),  $second = $('#second'),  value = $first.val(),  k = 3,  cookiestring = 'SOMECOOKIESPLEASE',  i,  j,  myArray = {};

5. 最好选择“on”(prefer 'On')

Recent versions of jQuery have changed whereby functions like click() are shorthand foron('click'). In prior versions the implementation was different whereby click() what shorthand for bind(). As of jQuery 1.7, on() is the preferred method for attaching event handlers. However, for consistency you can simply use on() across the board.

// bad code$first.click(function(){    $first.css('border','1px solid red');    $first.css('color','blue');});$first.hover(function(){    $first.css('border','1px solid red');})// better code$first.on('click',function(){    $first.css('border','1px solid red');    $first.css('color','blue');})$first.on('hover',function(){    $first.css('border','1px solid red');})

6. 使用链结构(use chaining)

Following on the above rule, jQuery makes it easy to chain mathods together. Take advantage of this.

// bad$second.html(value);$second.on('click',function(){    alert('hello everybody');});$second.fadeIn('slow');$second.animate({height:'120px'},500);// better$second.html(value);$second.on('click',function(){    alert('hello everybody');}).fadeIn('slow').animate({height:'120px'},500);

7. 保持代码的可读性(keep your code readable)

When trying to condense your scripts and utilize chaining, code can sometimes become unreadable. Try to utlize tabs and new lines to keep things looking pretty.

// bad code$second.html(value);$second.on('click',function(){    alert('hello everybody');}).fadeIn('slow').animate({height:'120px'},500);// better code$second.html(value);$second            .on('click',function(){ alert('hello everybody');})            .fadeIn('slow')            .animate({height:'120px'},500);

8. 使用短路循环(Prefer Short-circuiting)

 are expressions evaluated from left-to-right and use the &&(logical and) or || (logical or) operators.

// bad codefunction initVar($myVar) {    if(!$myVar) {        $myVar = $('#selector');    }}// better codefunction initVar($myVar) {    $myVar = $myVar || $('#selector');}

9. 使用简写(prefer shortcuts)

One of the ways to condense your code is to take advantage of coding shortcuts.

// badif(collection.length > 0){..}// betterif(collection.length){..}

10. 对元素进行大量操作时应选择拆卸(detach elements when doing heavy manipulations)

if you are going to do heavy manupipulation of a DOM element, it is recommended that you first detach it and then re-append it.

// bad codevar     $container = $("#container"),    $containerLi = $("#container li"),    $element = null;$element = $containerLi.first(); //... a lot of complicated things// better codevar     $container = $("#container"),    $containerLi = $container.find("li"),    $element = null;$element = $containerLi.first().detach(); //...a lot of complicated things$container.append($element);

11. 知道技巧(know the tricks)

When using methods within jQuery that you may have less experience with, be sure to check the  as there may be a preferable or faster way to use it.

// bad$('#id').data(key,value);// better (faster)$.data('#id',key,value);

12. 使用子查询缓存父元素(use subqueries caching parents)

As mentioned earlier, DOM traversal is an expensive operation. It is typically better to cache parent elements and reuse these cached elements when selecting child elements.

// badvar     $container = $('#container'),    $containerLi = $('#container li'),    $containerLiSpan = $('#container li span');// better (faster)var     $container = $('#container '),    $containerLi = $container.find('li'),    $containerLiSpan= $containerLi.find('span');

13. 避免通用选择器(avoid universal selectors)

When combined with other selectors, the universal selector is extremely slow.

// bad$('.container > *'); // better$('.container').children();

14. 避免默认通用选择器(avoid implied universal selectors)

When you leave off the selector, the universal selector (*) is still implied.

// bad$('.someclass :radio'); // better$('.someclass input:radio');

15. 优化选择器(optimize selectors)

for example, using an ID should already be sufficiently specific, so there is no need to add additional selector specificity.

// bad$('div#myid'); $('div#footer a.myLink');// better$('#myid');$('#footer .myLink');

16.  不要担心多个IDs(Dont descend mutiple IDs)

Again, when used properly, ID’s should be sufficiently specific not to require the additional specificity of multiple descendant selectors.

// bad$('#outer #inner'); // better$('#inner');

17.  不要用废弃的方法(Dont use deprecated Methods)

It is important to always keep an eye on  for each new version and try avoid using them.

// bad - live is deprecated$('#stuff').live('click', function() {  console.log('hooray');});// better$('#stuff').on('click', function() {  console.log('hooray');});

18. 从内容发布网络上加载jQuery code

The Google CDN quickly delivers the script from the user’s nearest cache location. To use the Google CDN, use the following url for this 

 

转载于:https://www.cnblogs.com/jassonfish/p/3526808.html

你可能感兴趣的文章
Factory Design Pattern
查看>>
P1192-台阶问题
查看>>
一、使用pip安装Python包
查看>>
Duilib扩展《01》— 双击、右键消息扩展
查看>>
网站产品设计
查看>>
go 学习笔记(4) ---项目结构
查看>>
java中静态代码块的用法 static用法详解
查看>>
Java线程面试题
查看>>
day22 01 初识面向对象----简单的人狗大战小游戏
查看>>
Flask三剑客
查看>>
Hibernate-缓存
查看>>
【BZOJ4516】生成魔咒(后缀自动机)
查看>>
提高PHP性能的10条建议
查看>>
svn“Previous operation has not finished; run 'cleanup' if it was interrupted“报错的解决方法...
查看>>
Java大数——a^b + b^a
查看>>
KDESVN中commit时出现containing working copy admin area is missing错误提示
查看>>
【动态规划】skiing
查看>>
java定时器的使用(Timer)
查看>>
ef codefirst VS里修改数据表结构后更新到数据库
查看>>
boost 同步定时器
查看>>