翻译自:http://lab.abhinayrathore.com/
翻译人员:前端开发whqet,意译为主,不当之处敬请指正。
译者说:临近期末,大部分的基础教学内容已经讲解完毕,在进行比较大型的项目训练之前,如果能让学生了解甚至遵循一些前端开发的编码规范将会是一件非常有意义的事情。因此,本博客准备于近期整理一个编码规范与最佳实践的系列文章,包括html、css、javascript、jquery、php等,希望能对大家有所帮助。
------------------------------------------------------------
--我参加了博客之星评选,如果你喜欢我的博客,求投票~~http://vote.blog.csdn.net/blogstar2014/details?username=whqet#content
-----------------------------------------------------------------------------------------
本文给大家呈现的如何书写更好的jQuery代码的相关规范和最佳实践,不包括javascript方面的规范,有好的意见和建议请大家到我的博客留言赐教,或者看看jQuery API的速查表(cheat sheet)。
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/jquery-2.1.1.min.js" type="text/javascript"><\/script>')</script>
var $myDiv = $("#myDiv");
$myDiv.click(function(){...});
var $products = $("div.products"); // SLOW
var $products = $(".products"); // FAST
// 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");
// Unoptimized
$("div.data .gonzalez");
// Optimized
$(".data td.gonzalez");
$(".data table.attendees td.gonzalez");
// Better: Drop the middle if possible.
$(".data td.gonzalez");
// SLOWER because it has to traverse the whole DOM for .class
$('.class');
// FASTER because now it only looks under class-container.
$('.class', '#class-container');
$('div.container > *'); // BAD
$('div.container').children(); // BETTER
$('div.someclass :radio'); // BAD
$('div.someclass input:radio'); // GOOD
$('#outer #inner'); // BAD
$('div#inner'); // BAD
$('.outer-container #inner'); // BAD
$('#inner'); // GOOD, only calls document.getElementById()
var $myList = $("#list-container > ul").detach();
//...a lot of complicated things on $myList
$myList.appendTo("#list-container");
// 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(''));
// 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();
}
$("#myLink").on("click", function(){...}); // BAD
// GOOD
function myLinkClickHandler(){...}
$("#myLink").on("click", myLLinkClickHandler);
$(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.
}
<script src="my-document-ready.js"></script>
<script>
// Any global variable set-up that might be needed.
$(document).ready(initPage); // or $(initPage);
</script>
<a id="myLink" href="#" οnclick="myEventHandler();">my link</a> <!-- BAD -->
$("#myLink").on("click", myEventHandler); // GOOD
$("#myLink").on("click.mySpecialClick", myEventHandler); // GOOD
// Later on, it's easier to unbind just your click event
$("#myLink").unbind("click.mySpecialClick");
$("#list a").on("click", myClickHandler); // BAD, you are attaching an event to all the links under the list.
$("#list").on("click", "a", myClickHandler); // GOOD, only one event handler is attached to the parent.
// Less readable...
$.ajax({
url: "something.php?param1=test1¶m2=test2",
....
});
// More readable...
$.ajax({
url: "something.php",
data: { param1: test1, param2: test2 }
});
$("#parent-container").on("click", "a", delegatedClickHandlerForAjax)
$.ajax({ ... }).then(successHandler, failureHandler);
// OR
var jqxhr = $.ajax({ ... });
jqxhr.done(successHandler);
jqxhr.fail(failureHandler);
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);
$("#myDiv").addClass("error").show();
$("#myLink")
.addClass("bold")
.on("click", myClickHandler)
.on("mouseover", myMouseOverHandler)
.show();
$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"
});
$("#mydiv").css({'color':red, 'font-weight':'bold'}); // BAD
.error { color: red; font-weight: bold; } /* GOOD */
$("#mydiv").addClass("error"); // GOOD
$("#myId"); // is still little slower than...
document.getElementById("myId");
Enjoy it.
----------------------------------------------------------
前端开发whqet,关注web前端开发,分享相关资源,欢迎点赞,欢迎拍砖。
---------------------------------------------------------------------------------------------------------