Jquery编码便准最佳实践

不知道在哪里看到了这篇关于jQuery编码的文章,挺实用的,恰好最近在研究jQuery的基础知识,今天打开收藏夹来翻译一下,原文的英语不难,但是内容很实用,可能有大神已经翻译过了,大家看精华就行了。

加载jQuery

1. 尽量在页面上使用CDN来加载jQuery。 CDN Benefits,一些流行的CDN地址

?
1
2
<script type= "text/javascript" <br>src= "//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" ></script>
<script>window.jQuery || document.write( '<script src="js/jquery-1.11.0.min.js" <br>type="text/javascript"><\/script>' )</script>

2. 最好在本地提供一个和CDN上相同版本的jQuery库,像上面那样。更多详情

3. 使用 protocol-relative/protocol-independent 的url(去掉http:和https:),就像上面那样。

4. 尽可能的保持你的javascript和jQuery代码放在页面的底部。更多信息HTML5的样本文件的一些例子。

5. 该用哪个版本?

  • 如果支持IE6/7/8,那就不要使用版本2.x
  • 对于新的web-apps来说,如果你没有插件兼容性的问题,那么强烈建议你使用最新版本的jQuery。
  • 当你加载来自CDN上的jQuery时,你要指定你要加载的jQuery的完整版本号(像  1.11.0不要写成1.11或者1)。
  • 不要加载多个不同版本的jQuery。

6. 如果你想要使用其他的库,像Prototype,MooTools,Zapto等,它们同样是使用$符号,那么尽量不要使用$来调用jQuery的函数,使用jQuery来代替$。你也可以通过$.onConfilict()来将$的控制器还给其他的库。

7. 对浏览器的新特性多检测,使用Modernizr

jQuery的变量

1. 所有用来存储/缓存jQuery对象的变量的名字应该有一个前缀$。

2. 在变量中缓存jQuery选择器返回的内容以便重用。

?
1
2
<br> var $myDiv = $( "#myDiv" );
$myDiv.click( function (){...});<br>

3. 使用驼峰规则命名变量。

选择器

1. 在任何时候尽可能的使用ID,这是比较快的因为它使用document.getElementById()处理的。

2. 当使用类选择器的时候,不要在类选择器中指定元素的类型。性能比较

?
1
2
var $products = $( "div.products" ); // SLOW
var $products = $( ".products" ); // FAST

3. 对于id->child这种嵌套的选择器要使用find来查找。find()方法比较快是由于第一个选择符(id)不会通过Sizzle的处理,更多详情

?
1
2
3
4
5
// BAD, a nested query for Sizzle selector engine
var $productIds = $( "#products div.id" );
// GOOD, #products is already selected by document.getElementById() so only div.id needs to go through Sizzle selector engine
var $productIds = $( "#products" ).find( "div.id" );

4. 在你的选择器的右侧尽量的详细,左侧尽量的简单,更多信息

?
1
2
3
4
5
// Unoptimized
$( "div.data .gonzalez" );
// Optimized
$( ".data td.gonzalez" );

5. 避免过度的详细,更多详情,性能比较

?
1
2
3
4
$( ".data table.attendees td.gonzalez" );
// Better: Drop the middle if possible.
$( ".data td.gonzalez" );

6. 给选择器一个上下文。

?
1
2
3
4
5
// SLOWER because it has to traverse the whole DOM for .class
$( '.class' );
// FASTER because now it only looks under class-container.
$( '.class' , '#class-container' );

7. 避免使用通用选择符*。更多信息

?
1
2
$( 'div.container > *' ); // BAD
$( 'div.container' ).children(); // BETTER

8. 避免使用隐式的通用选择符。当你漏下了一些选择器,通用选择器(*)仍然是隐含存在的。更多信息

?
1
2
$( 'div.someclass :radio' ); // BAD
$( 'div.someclass input:radio' ); // GOOD

9. 在使用ID时不要指定多个ID,ID选择器是通过document.getElementById()处理的,所以不要和其他的选择符混着使用。

?
1
2
3
4
$( '#outer #inner' ); // BAD
$( 'div#inner' ); // BAD
$( '.outer-container #inner' ); // BAD
$( '#inner' ); // GOOD, only calls document.getElementById()

DOM操作处理

1. 在操作处理DOM之前要先将已经存在的元素卸载分离下来,待操作完之后再将其挂回去。更多详情

?
1
2
3
var $myList = $( "#list-container > ul" ).detach();
//...a lot of complicated things on $myList
$myList.appendTo( "#list-container" );

2. 使用字符串连接或者array.join()不要使用append()。更多详情性能比较

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// BAD
var $myList = $( "#list" );
for ( var i = 0; i < 10000; i++){
$myList.append( "<li>" +i+ "</li>" );
}
// GOOD
var $myList = $( "#list" );
var list = "" ;
for ( var i = 0; i < 10000; i++){
list += "<li>" +i+ "</li>" ;
}
$myList.html(list);
// EVEN FASTER
var array = [];
for ( var i = 0; i < 10000; i++){
array[i] = "<li>" +i+ "</li>" ;
}
$myList.html(array.join( '' ));

3. 不要在不存在的元素上进行操作。更多详情

?
1
2
3
4
5
6
7
8
// BAD: This runs three functions before it realizes there's nothing in the selection
$( "#nosuchthing" ).slideUp();
// GOOD
var $mySelection = $( "#nosuchthing" );
if ($mySelection.length) {
$mySelection.slideUp();
}

事件

1. 每一个页面上只使用一个文档的ready事件处理函数。这样会更容易进行调试和跟踪动作的流程。

2. 不要使用匿名函数来绑定事件。匿名函数很难进行调试,维护,测试和重用。更多详情

?
1
2
3
4
5
$( "#myLink" ).on( "click" , function (){...}); // BAD
// GOOD
function myLinkClickHandler(){...}
$( "#myLink" ).on( "click" , myLinkClickHandler);

3. 处理文档ready事件的回调也不要使用匿名函数。在一次强调,匿名函数很难进行调试,维护,测试和重用。

?
1
2
3
4
5
6
7
$( function (){ ... }); // BAD: You can never reuse or write a test for this function.
// GOOD
$(initPage); // or $(document).ready(initPage);
function initPage(){
// Page load event where you can initialize values and call other initializers.
}

4. 文档ready事件的处理函数应该包含在外部的javascript文件中,内联的javascript应该在初始化之后直接调用处理函数。

?
1
2
3
4
5
<script src= "my-document-ready.js" ></script>
<script>
// Any global variable set-up that might be needed.
$(document).ready(initPage); // or $(initPage);
</script>

5. 不要在HTML中写javascript的内联代码,这是调试的噩梦。要使用jQuery来绑定事件这样很容易动态的添加和移除事件。

?
1
2
3
<a id= "myLink" href= "#" onclick= "myEventHandler();" >my link</a> <!-- BAD -->
$( "#myLink" ).on( "click" , myEventHandler); // GOOD

6. 尽可能给事件添加命名空间,这样就会很容易移除你绑定过的事件而不会影响其他的绑定的事件。

?
1
2
3
4
$( "#myLink" ).on( "click.mySpecialClick" , myEventHandler); // GOOD
// Later on, it's easier to unbind just your click event
$( "#myLink" ).unbind( "click.mySpecialClick" );

AJAX

1. 避免使用.getJson()和.get(),就简单的使用$.ajax(),因为这就是.get()内部调用的东西。

2. 不要在https的网站上使用http请求。更好的使用无模式的url(将HTTP或者HTTPS从你的URL中移除)。

3. 不要在URL上发送请求参数,用数据对象来发送它们。

?
1
2
3
4
5
6
7
8
9
10
11
// Less readable...
$.ajax({
url: "something.php?param1=test1&param2=test2" ,
....
});
// More readable...
$.ajax({
url: "something.php" ,
data: { param1: test1, param2: test2 }
});

4. 尽量指定dataType,这样可以容易的知道你要出来哪种类型的数据(看下面Ajax的模板例子)

5. 使用事件代理来将事件绑定到使用Ajax加载的内容上,事件代理在异步加载上有优势,它可以处理来自过一段时间之后加载到文档中的后代元素的事件。

?
1
$( "#parent-container" ).on( "click" , "a" , delegatedClickHandlerForAjax);

6. 使用Promise接口。更多例子

?
1
2
3
4
5
6
$.ajax({ ... }).then(successHandler, failureHandler);
// OR
var jqxhr = $.ajax({ ... });
jqxhr.done(successHandler);
jqxhr.fail(failureHandler);

7. Ajax模板例子。 更多信息

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
var jqxhr = $.ajax({
url: url,
type: "GET" , // default is GET but you can use other verbs based on your needs.
cache: true , // default is true, but false for dataType 'script' and 'jsonp', so set it on need basis.
data: {}, // add your request parameters in the data object.
dataType: "json" , // specify the dataType for future reference
jsonp: "callback" , // only specify this to match the name of callback parameter your API is expecting for JSONP requests.
statusCode: { // if you want to handle specific error codes, use the status code mapping settings.
404: handler404,
500: handler500
}
});
jqxhr.done(successHandler);
jqxhr.fail(failureHandler);

效果和动画

1. 采取一致的方法来实现动画功能。

2. 不要过度做动画效果,要满足用户体验的需求。

  • 尽量使用简单的show/hide, toggle and slideUp/slideDown 来显示和隐藏一个元素。
  • 使用预设值来设置动画的速度'fast','slow',或者400(medium)

插件

1. 要始终选择一个有良好支持,完善文档,全面测试过并且社区活跃的插件。

2. 检测所用插件与当前使用的jQuery版本是否兼容。

3. 一些常用功能应该写成jQuery插件。jQuery插件模板例子

链式语法

1. 使用链式语法作为替代变量缓存和多个选择器调用。

?
1
$( "#myDiv" ).addClass( "error" ).show();

2. 当你的链调用超过3个或者由于事件的指定变得复杂了,使用换行和适当的缩进来提高代码的可读性。

?
1
2
3
4
5
$( "#myLink" )
.addClass( "bold" )
.on( "click" , myClickHandler)
.on( "mouseover" , myMouseOverHandler)
.show();

3. 对于特别长的链式调用最好还是用变量保存下中间结果来简化代码

杂项

1. 使用对象字面量

?
1
2
3
4
5
6
7
$myLink.attr( "href" , "#" ).attr( "title" , "my link" ).attr( "rel" , "external" ); // BAD, 3 calls to attr()
// GOOD, only 1 call to attr()
$myLink.attr({
href: "#" ,
title: "my link" ,
rel: "external"
});

2. 不要将CSS和jQuery混在一起。

?
1
2
3
4
5
$( "#mydiv" ).css({ 'color' :red, 'font-weight' : 'bold' });
.error { color: red; font-weight: bold; } /* GOOD */
$( "#mydiv" ).addClass( "error" ); // GOOD

3. 不要使用被弃用的方法,关注每一个新的版本上一些弃用的方法尽量避免使用它们是很重要的。这里有一些被弃用的方法的列表

4. 需要的话将原生的javascript代码和jQuery代码合并。看一下性能的比较

?
1
2
$( "#myId" ); // is still little slower than...
document.getElementById( "myId" );

原文地址:http://lab.abhinayrathore.com/jquery-standards/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值