加载中...

4.2. jQuery 规范


使用最新版本的 jQuery

最新版本的 jQuery 会改进性能和增加新功能,若不是为了兼容旧浏览器,建议使用最新版本的 jQuery。以下是三条常见的 jQuery 语句,版本越新,性能越好:

  1. $('.elem')
  2. $('.elem', context)
  3. context.find('.elem')

分别使用 1.4.2、1.4.4、1.6.2 三个版本测试浏览器在一秒内能够执行多少次,结果 1.6.2 版执行次数远超两个老版本。

jQuery 变量

  1. 存放 jQuery 对象的变量以 $ 开头;
  2. 将 jQuery 选择器返回的对象缓存到本地变量中复用;
  3. 使用驼峰命名变量;
  1. var $myDiv = $("#myDiv");
  2. $myDiv.click(function(){...});

选择器

  1. 尽可能的使用 ID 选择器,因为它会调用浏览器原生方法 document.getElementById 查找元素。当然直接使用原生 document.getElementById 方法性能会更好;
  2. 在父元素中选择子元素使用 .find() 方法性能会更好, 因为 ID 选择器没有使用到 Sizzle 选择器引擎来查找元素;
  1. // Not recommended
  2. var $productIds = $("#products .class");
  3.  
  4. // Recommended
  5. var $productIds = $("#products").find(".class");

DOM 操作

  1. 当要操作 DOM 元素的时候,尽量将其分离节点,操作结束后,再插入节点;
  2. 使用字符串连接或 array.join 要比 .append()性能更好;
  1. var $myList = $("#list-container > ul").detach();
  2. //...a lot of complicated things on $myList
  3. $myList.appendTo("#list-container");
  1. // Not recommended
  2. var $myList = $("#list");
  3. for(var i = 0; i < 10000; i++){
  4.     $myList.append("<li>"+i+"</li>");
  5. }
  6.  
  7. // Recommended
  8. var $myList = $("#list");
  9. var list = "";
  10. for(var i = 0; i < 10000; i++){
  11.     list += "<li>"+i+"</li>";
  12. }
  13. $myList.html(list);
  14.  
  15. // Much to recommended
  16. var array = [];
  17. for(var i = 0; i < 10000; i++){
  18.     array[i] = "<li>"+i+"</li>";
  19. }
  20. $myList.html(array.join(''));

事件

  1. 如果需要,对事件使用自定义的 namespace,这样容易解绑特定的事件,而不会影响到此 DOM 元素的其他事件监听;
  2. 对 Ajax 加载的 DOM 元素绑定事件时尽量使用事件委托。事件委托允许在父元素绑定事件,子代元素可以响应事件,也包括 Ajax 加载后添加的子代元素;
  1. $("#myLink").on("click.mySpecialClick", myEventHandler);
  2. $("#myLink").unbind("click.mySpecialClick");
  1. // Not recommended
  2. $("#list a").on("click", myClickHandler);
  3.  
  4. // Recommended
  5. $("#list").on("click", "a", myClickHandler);

链式写法

  1. 尽量使用链式写法而不是用变量缓存或者多次调用选择器方法;
  2. 当链式写法超过三次或者因为事件绑定变得复杂后,使用换行和缩进保持代码可读性;
  1. $("#myDiv").addClass("error").show();
  1. $("#myLink")
  2.   .addClass("bold")
  3.   .on("click", myClickHandler)
  4.   .on("mouseover", myMouseOverHandler)
  5.   .show();

其他

  1. 多个参数使用对象字面量存储;
  2. 不要将 CSS 写在 jQuery 里面;
  3. 正则表达式仅准用 .test() 和 .exec() 。不准用 "string".match() ;

jQuery 插件模板

  1. // jQuery Plugin Boilerplate
  2. // A boilerplate for jumpstarting jQuery plugins development
  3. // version 1.1, May 14th, 2011
  4. // by Stefan Gabos
  5.  
  6. // remember to change every instance of "pluginName" to the name of your plugin!
  7. (function($) {
  8.  
  9.     // here we go!
  10.     $.pluginName = function(element, options) {
  11.  
  12.         // plugin's default options
  13.         // this is private property and is  accessible only from inside the plugin
  14.         var defaults = {
  15.  
  16.             foo: 'bar',
  17.  
  18.             // if your plugin is event-driven, you may provide callback capabilities
  19.             // for its events. execute these functions before or after events of your
  20.             // plugin, so that users may customize those particular events without
  21.             // changing the plugin's code
  22.             onFoo: function() {}
  23.  
  24.         }
  25.  
  26.         // to avoid confusions, use "plugin" to reference the
  27.         // current instance of the object
  28.         var plugin = this;
  29.  
  30.         // this will hold the merged default, and user-provided options
  31.         // plugin's properties will be available through this object like:
  32.         // plugin.settings.propertyName from inside the plugin or
  33.         // element.data('pluginName').settings.propertyName from outside the plugin,
  34.         // where "element" is the element the plugin is attached to;
  35.         plugin.settings = {}
  36.  
  37.         var $element = $(element), // reference to the jQuery version of DOM element
  38.              element = element;    // reference to the actual DOM element
  39.  
  40.         // the "constructor" method that gets called when the object is created
  41.         plugin.init = function() {
  42.  
  43.             // the plugin's final properties are the merged default and
  44.             // user-provided options (if any)
  45.             plugin.settings = $.extend({}, defaults, options);
  46.  
  47.             // code goes here
  48.  
  49.         }
  50.  
  51.         // public methods
  52.         // these methods can be called like:
  53.         // plugin.methodName(arg1, arg2, ... argn) from inside the plugin or
  54.         // element.data('pluginName').publicMethod(arg1, arg2, ... argn) from outside
  55.         // the plugin, where "element" is the element the plugin is attached to;
  56.  
  57.         // a public method. for demonstration purposes only - remove it!
  58.         plugin.foo_public_method = function() {
  59.  
  60.             // code goes here
  61.  
  62.         }
  63.  
  64.         // private methods
  65.         // these methods can be called only from inside the plugin like:
  66.         // methodName(arg1, arg2, ... argn)
  67.  
  68.         // a private method. for demonstration purposes only - remove it!
  69.         var foo_private_method = function() {
  70.  
  71.             // code goes here
  72.  
  73.         }
  74.  
  75.         // fire up the plugin!
  76.         // call the "constructor" method
  77.         plugin.init();
  78.  
  79.     }
  80.  
  81.     // add the plugin to the jQuery.fn object
  82.     $.fn.pluginName = function(options) {
  83.  
  84.         // iterate through the DOM elements we are attaching the plugin to
  85.         return this.each(function() {
  86.  
  87.             // if plugin has not already been attached to the element
  88.             if (undefined == $(this).data('pluginName')) {
  89.  
  90.                 // create a new instance of the plugin
  91.                 // pass the DOM element and the user-provided options as arguments
  92.                 var plugin = new $.pluginName(this, options);
  93.  
  94.                 // in the jQuery version of the element
  95.                 // store a reference to the plugin object
  96.                 // you can later access the plugin and its methods and properties like
  97.                 // element.data('pluginName').publicMethod(arg1, arg2, ... argn) or
  98.                 // element.data('pluginName').settings.propertyName
  99.                 $(this).data('pluginName', plugin);
  100.  
  101.             }
  102.  
  103.         });
  104.  
  105.     }
  106.  
  107. })(jQuery);

此 jQuery 插件模板出自:jQuery Plugin Boilerplate, revisited


还没有评论.