`

工程师,请优化你的代码(转载)

    博客分类:
  • JS
 
阅读更多
  1. Ajax
  2. jQuery ready事件
  3. 事件处理
  4. DOM操作

 

 

Ajax

 

大部分项目这么写:

Js代码 复制代码 收藏代码
  1. function getName(personid) {
  2. var dynamicData = {};
  3. dynamicData["id"] = personID;
  4. $.ajax({
  5. url: "getName.php",
  6. type: "get",
  7. data: dynamicData,
  8. success: function(data) {
  9. // Updates the UI based the ajax result
  10. $(".person-name").text(data.name);
  11. }
  12. });
  13. }
  14. getName("2342342");
 function getName(personid) {
    var dynamicData = {};
    dynamicData["id"] = personID;
    $.ajax({
      url: "getName.php",
      type: "get",
      data: dynamicData,
      success: function(data) {
        // Updates the UI based the ajax result
        $(".person-name").text(data.name);  
      }
    });
  }

  getName("2342342");

 

最佳实践:

Js代码 复制代码 收藏代码
  1. function getName(personid) {
  2. var dynamicData = {};
  3. dynamicData["id"] = personid;
  4. return $.ajax({
  5. url: "getName.php",
  6. type: "get",
  7. data: dynamicData
  8. });
  9. }
  10. getName("2342342").done(function(data) {
  11. // Updates the UI based the ajax result
  12. $(".person-name").text(data.name);
  13. });
function getName(personid) {
    var dynamicData = {};
    dynamicData["id"] = personid;
    return $.ajax({
      url: "getName.php",
      type: "get",
      data: dynamicData
    });
  }

  getName("2342342").done(function(data) {
    // Updates the UI based the ajax result
    $(".person-name").text(data.name); 
  });

非常灵活

 

jQuery ready事件

 

大部分项目用这段代码做闭包

 

Js代码 复制代码 收藏代码
  1. $("document").ready(function() {
  2. // The DOM is ready!
  3. // The rest of the code goes here
  4. });
 $("document").ready(function() {
    // The DOM is ready!
    // The rest of the code goes here
  });

或者用简写

 

 

Js代码 复制代码 收藏代码
  1. $(function() {
  2. // The DOM is ready!
  3. // The rest of the code goes here
  4. });
$(function() {
    // The DOM is ready!
    // The rest of the code goes here
});

 

  • 如果你清楚代码的执行环境
  • 如果你不关注页面加载性能
  • 如果你不关注最佳实践

。。。这么写就没问题

 

更好的写法是

Js代码 复制代码 收藏代码
  1. // IIFE - Immediately Invoked Function Expression
  2. (function($, window, document) {
  3. // The $ is now locally scoped
  4. // Listen for the jQuery ready event on the document
  5. $(function() {
  6. // The DOM is ready!
  7. });
  8. // The rest of the code goes here!
  9. }(window.jQuery, window, document));
  10. // The global jQuery object is passed as a parameter
// IIFE - Immediately Invoked Function Expression
  (function($, window, document) {

    // The $ is now locally scoped 

   // Listen for the jQuery ready event on the document
   $(function() {

     // The DOM is ready!

   });

   // The rest of the code goes here!

  }(window.jQuery, window, document));
  // The global jQuery object is passed as a parameter

 

更进一步,最佳写法:

Js代码 复制代码 收藏代码
  1. // IIFE - Immediately Invoked Function Expression
  2. (function(yourcode) {
  3. // The global jQuery object is passed as a parameter
  4. yourcode(window.jQuery, window, document);
  5. }(function($, window, document) {
  6. // The $ is now locally scoped
  7. // Listen for the jQuery ready event on the document
  8. $(function() {
  9. // The DOM is ready!
  10. }));
// IIFE - Immediately Invoked Function Expression
  (function(yourcode) {

    // The global jQuery object is passed as a parameter
  	yourcode(window.jQuery, window, document);

  }(function($, window, document) {

    // The $ is now locally scoped 

   // Listen for the jQuery ready event on the document
   $(function() {

     // The DOM is ready!

   }));

 

 

 

事件处理

 

大部分项目这么写:

Js代码 复制代码 收藏代码
  1. $("#longlist li").on("mouseenter", function() {
  2. $(this).text("Click me!");
  3. });
  4. $("#longlist li").on("click", function() {
  5. $(this).text("Why did you click me?!");
  6. });
  $("#longlist li").on("mouseenter", function() {

    $(this).text("Click me!");

  });

  $("#longlist li").on("click", function() {

    $(this).text("Why did you click me?!");

  });

 

更好的写法:

Js代码 复制代码 收藏代码
  1. var listItems = $("#longlist li");
  2. listItems.on({
  3. "mouseenter": function() {
  4. $(this).text("Click me!");
  5. },
  6. "click": function() {
  7. $(this).text("Why did you click me?!");
  8. }
  9. });
 var listItems = $("#longlist li");
  listItems.on({

    "mouseenter": function() {

      $(this).text("Click me!");

    },

    "click": function() {

      $(this).text("Why did you click me?!");

    }

  });

DRY ( Don't repeat yourself. )

 

最佳实践:

Js代码 复制代码 收藏代码
  1. var list = $("#longlist");
  2. list.on("mouseenter", "li", function(){
  3. $(this).text("Click me!");
  4. });
  5. list.on("click", "li", function() {
  6. $(this).text("Why did you click me?!");
  7. });
var list = $("#longlist");

  list.on("mouseenter", "li", function(){

    $(this).text("Click me!");

  });

  list.on("click", "li", function() {

    $(this).text("Why did you click me?!");

  });

使用事件代理(Event Delegation)

 

DOM操作

大部分项目这么写:

Js代码 复制代码 收藏代码
  1. $('.class1').click(function() {
  2. some_function();
  3. });
  4. $('.class2').click(function() {
  5. some_function();
  6. });
$('.class1').click(function() {
   some_function();
});

$('.class2').click(function() {
   some_function();
});

 

  • 如果你喜欢重复的编码
  • 如果你不关心代码性能
  • 如果你不关注最佳实践

更好的实现方法:

Js代码 复制代码 收藏代码
  1. $('.class1').$('.class2').click(function() {
  2. some_function();
  3. });
$('.class1').$('.class2').click(function() {
   some_function();
});

 

大部分项目这么写:

Js代码 复制代码 收藏代码
  1. / Set's an element's title attribute using it's current text
  2. $(".container input#elem").attr("title", $(".container input#elem").text());
  3. // Set's an element's text color to red
  4. $(".container input#elem").css("color", "red");
  5. // Makes the element fade out
  6. $(".container input#elem").fadeOut();
/ Set's an element's title attribute using it's current text
  $(".container input#elem").attr("title", $(".container input#elem").text());

  // Set's an element's text color to red
  $(".container input#elem").css("color", "red");

  // Makes the element fade out
  $(".container input#elem").fadeOut();

 

  • 如果你喜欢重复的编码
  • 如果你不关心代码性能
  • 如果你不关注最佳实践

。。。这么写没问题

 

更好的实现方法:

Java代码 复制代码 收藏代码
  1. // Set's an element's title attribute using it's current text
  2. $("#elem").attr("title", $("#elem").text());
  3. // Set's an element's text color to red
  4. $("#elem").css("color", "red");
  5. // Makes the element fade out
  6. $("#elem").fadeOut();
// Set's an element's title attribute using it's current text
  $("#elem").attr("title", $("#elem").text());

  // Set's an element's text color to red
  $("#elem").css("color", "red");

  // Makes the element fade out
  $("#elem").fadeOut();

简化你的选择器

 

最佳实践:

Js代码 复制代码 收藏代码
  1. // Stores the live DOM element inside of a variable
  2. var elem = $("#elem");
  3. // Set's an element's title attribute using it's current text
  4. elem.attr("title", elem.text());
  5. // Set's an element's text color to red
  6. elem.css("color", "red");
  7. // Makes the element fade out
  8. elem.fadeOut();
  // Stores the live DOM element inside of a variable
  var elem = $("#elem");

  // Set's an element's title attribute using it's current text
  elem.attr("title", elem.text());

  // Set's an element's text color to red
  elem.css("color", "red");

  // Makes the element fade out
  elem.fadeOut();

使用变量缓存你的选择器

 

或者是用更简单的写法:

Js代码 复制代码 收藏代码
  1. // Stores the live DOM element inside of a variable
  2. var elem = $("#elem");
  3. // Chaining
  4. elem.attr("title", elem.text()).css("color", "red").fadeOut();
// Stores the live DOM element inside of a variable
  var elem = $("#elem");

  // Chaining
  elem.attr("title", elem.text()).css("color", "red").fadeOut();

使用链式调用

 

另外一个操作DOM的示例

大部分项目这么写:

Js代码 复制代码 收藏代码
  1. // Dynamically building an unordered list from an array
  2. var localArr = ["Greg", "Peter", "Kyle", "Danny", "Mark"],
  3. list = $("ul.people");
  4. $.each(localArr, function(index, value) {
  5. list.append("<li id=" + index + ">" + value + "</li>");
  6. });
// Dynamically building an unordered list from an array
  var localArr = ["Greg", "Peter", "Kyle", "Danny", "Mark"],
  	list = $("ul.people");

  $.each(localArr, function(index, value) {

    list.append("<li id=" + index + ">" + value + "</li>");

  });

最佳实践:只append一次

Js代码 复制代码 收藏代码
  1. // Dynamically building an unordered list from an array
  2. var localArr = ["Greg", "Peter", "Kyle", "Danny", "Mark"],
  3. list = $("ul.people"),
  4. dynamicItems = "";
  5. $.each(localArr, function(index, value) {
  6. dynamicItems += "<li id=" + index + ">" + value + "</li>";
  7. });
  8. list.append(dynamicItems);
// Dynamically building an unordered list from an array
  var localArr = ["Greg", "Peter", "Kyle", "Danny", "Mark"],
  	list = $("ul.people"),
  	dynamicItems = "";

  $.each(localArr, function(index, value) {

    dynamicItems += "<li id=" + index + ">" + value + "</li>";

  });

  list.append(dynamicItems);

 

 

 

 

参考资料:

http://gregfranko.com/jquery-best-practices/

http://stackoverflow.com/questions/18307078/jquery-best-practises-in-case-of-document-ready

http://gregfranko.com/jquery-best-practices/#/29

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics