• jQuery 规范
    • 使用最新版本的 jQuery
    • jQuery 变量
    • 选择器
    • DOM 操作
    • 事件
    • 链式写法
    • 其他
    • jQuery 插件模板

    jQuery 规范

    使用最新版本的 jQuery

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

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

    jQuery 规范 - 图1
    分别使用 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. // Recommended
    4. 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. // Recommended
    7. var $myList = $("#list");
    8. var list = "";
    9. for(var i = 0; i < 10000; i++){
    10. list += "<li>"+i+"</li>";
    11. }
    12. $myList.html(list);
    13. // Much to recommended
    14. var array = [];
    15. for(var i = 0; i < 10000; i++){
    16. array[i] = "<li>"+i+"</li>";
    17. }
    18. $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. // Recommended
    4. $("#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. // remember to change every instance of "pluginName" to the name of your plugin!
    6. (function($) {
    7. // here we go!
    8. $.pluginName = function(element, options) {
    9. // plugin's default options
    10. // this is private property and is accessible only from inside the plugin
    11. var defaults = {
    12. foo: 'bar',
    13. // if your plugin is event-driven, you may provide callback capabilities
    14. // for its events. execute these functions before or after events of your
    15. // plugin, so that users may customize those particular events without
    16. // changing the plugin's code
    17. onFoo: function() {}
    18. }
    19. // to avoid confusions, use "plugin" to reference the
    20. // current instance of the object
    21. var plugin = this;
    22. // this will hold the merged default, and user-provided options
    23. // plugin's properties will be available through this object like:
    24. // plugin.settings.propertyName from inside the plugin or
    25. // element.data('pluginName').settings.propertyName from outside the plugin,
    26. // where "element" is the element the plugin is attached to;
    27. plugin.settings = {}
    28. var $element = $(element), // reference to the jQuery version of DOM element
    29. element = element; // reference to the actual DOM element
    30. // the "constructor" method that gets called when the object is created
    31. plugin.init = function() {
    32. // the plugin's final properties are the merged default and
    33. // user-provided options (if any)
    34. plugin.settings = $.extend({}, defaults, options);
    35. // code goes here
    36. }
    37. // public methods
    38. // these methods can be called like:
    39. // plugin.methodName(arg1, arg2, ... argn) from inside the plugin or
    40. // element.data('pluginName').publicMethod(arg1, arg2, ... argn) from outside
    41. // the plugin, where "element" is the element the plugin is attached to;
    42. // a public method. for demonstration purposes only - remove it!
    43. plugin.foo_public_method = function() {
    44. // code goes here
    45. }
    46. // private methods
    47. // these methods can be called only from inside the plugin like:
    48. // methodName(arg1, arg2, ... argn)
    49. // a private method. for demonstration purposes only - remove it!
    50. var foo_private_method = function() {
    51. // code goes here
    52. }
    53. // fire up the plugin!
    54. // call the "constructor" method
    55. plugin.init();
    56. }
    57. // add the plugin to the jQuery.fn object
    58. $.fn.pluginName = function(options) {
    59. // iterate through the DOM elements we are attaching the plugin to
    60. return this.each(function() {
    61. // if plugin has not already been attached to the element
    62. if (undefined == $(this).data('pluginName')) {
    63. // create a new instance of the plugin
    64. // pass the DOM element and the user-provided options as arguments
    65. var plugin = new $.pluginName(this, options);
    66. // in the jQuery version of the element
    67. // store a reference to the plugin object
    68. // you can later access the plugin and its methods and properties like
    69. // element.data('pluginName').publicMethod(arg1, arg2, ... argn) or
    70. // element.data('pluginName').settings.propertyName
    71. $(this).data('pluginName', plugin);
    72. }
    73. });
    74. }
    75. })(jQuery);

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