jquery 编程的最佳实践

Loading jQuery

Always try to use a CDN to include jQuery on your page.

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script>window.jQuery || document.write(‘<script src="http://www.qixoo.qixoo.com/js/jquery-2.1.4.min.js" type="text/javascript"><\/script>‘)</script>

for a list of popular jQuery CDNs.
    Implement a fallback to your locally hosted library of same version as shown above.
    Use  URL (leave http: or https: out) as shown above.
    If possible, keep all your JavaScript and jQuery includes at the bottom of your page.  and a sample on .
    What version to use?
        DO NOT use jQuery version 2.x if you support Internet Explorer 6/7/8.
        For new web-apps, if you do not have any plugin compatibility issue, it‘s highly recommended to use the latest jQuery version.
        When loading jQuery from CDN‘s, always specify the complete version number you want to load (Example: 1.11.0 as opposed to 1.11 or just 1).
        DO NOT load multiple jQuery versions.
        DO NOT use .
    If you are using other libraries like Prototype, MooTools, Zepto etc. that uses $ sign as well, try not to use $ for calling jQuery functions and instead use jQuery simply. You can return control of $ back to the other library with a call to $.noConflict().
    For advanced browser feature detection, use .

jQuery Variables

All variables that are used to store/cache jQuery objects should have a name prefixed with a $.
    Always cache your jQuery selector returned objects in variables for reuse.

var $myDiv = $("#myDiv");
    $myDiv.click(function(){...});

Use  for naming variables.

Selectors

Use ID selector whenever possible. It is faster because they are handled using document.getElementById().
    When using class selectors, don‘t use the element type in your selector.

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

Use find for Id->Child nested selectors. The .find() approach is faster because the first selection is handled without going through the Sizzle selector engine.

// 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");

Be specific on the right-hand side of your selector, and less specific on the left.

// Unoptimized
    $("div.data .gonzalez");

// Optimized
    $(".data td.gonzalez");

Avoid Excessive Specificity. ,

$(".data table.attendees td.gonzalez");
     
    // Better: Drop the middle if possible.
    $(".data td.gonzalez");

Give your Selectors a Context.

// SLOWER because it has to traverse the whole DOM for .class
    $(‘.class‘);

// FASTER because now it only looks under class-container.
    $(‘.class‘, ‘#class-container‘);

Avoid Universal Selectors.

$(‘div.container > *‘); // BAD
    $(‘div.container‘).children(); // BETTER

Avoid Implied Universal Selectors. When you leave off the selector, the universal selector (*) is still implied.

$(‘div.someclass :radio‘); // BAD
    $(‘div.someclass input:radio‘); // GOOD

Don’t Descend Multiple IDs or nest when selecting an ID. ID-only selections are handled using document.getElementById() so don‘t mix them with other selectors.

$(‘#outer #inner‘); // BAD
    $(‘div#inner‘); // BAD
    $(‘.outer-container #inner‘); // BAD
    $(‘#inner‘); // GOOD, only calls document.getElementById()

DOM Manipulation

Always detach any existing element before manipulation and attach it back after manipulating it.

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

Use string concatenation or array.join() over .append().  
    Performance comparison:

// 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(‘‘));

Don’t Act on Absent Elements.

// 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();
    }

Events

Use only one Document Ready handler per page. It makes it easier to debug and keep track of the behavior flow.
    DO NOT use anonymous functions to attach events. Anonymous functions are difficult to debug, maintain, test, or reuse.

$("#myLink").on("click", function(){...}); // BAD
     
    // GOOD
    function myLinkClickHandler(){...}
    $("#myLink").on("click", myLinkClickHandler);

Document ready event handler should not be an anonymous function. Once again, anonymous functions are difficult to debug, maintain, test, or reuse.

$(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.
    }

Document ready event handlers should be included from external files and inline JavaScript can be used to call the ready handle after any initial setup.

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

DO NOT use behavioral markup in HTML (JavaScript inlining), these are debugging nightmares. Always bind events with jQuery to be consistent so it‘s easier to attach and remove events dynamically.

<a id="myLink" href="#" onclick="myEventHandler();">my link</a> <!-- BAD -->

$("#myLink").on("click", myEventHandler); // GOOD

When possible, use custom  for events. It‘s easier to unbind the exact event that you attached without affecting other events bound to the DOM element.

$("#myLink").on("click.mySpecialClick", myEventHandler); // GOOD
    // Later on, it‘s easier to unbind just your click event
    $("#myLink").unbind("click.mySpecialClick");

Use  when you have to attach same event to multiple elements. Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

$("#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.

Ajax

Avoid using .getJson() or .get(), simply use the $.ajax() as that‘s what gets called internally.
    DO NOT use http requests on https sites. Prefer schemaless URLs (leave the protocol http/https out of your URL)
    DO NOT put request parameters in the URL, send them using data object setting.

// Less readable...
    $.ajax({
        url: "something.php?param1=test1&param2=test2",
        ....
    });
     
    // More readable...
    $.ajax({
        url: "something.php",
        data: { param1: test1, param2: test2 }
    });

Try to specify the dataType setting so it‘s easier to know what kind of data you are working with. (See Ajax Template example below)
    Use Delegated event handlers for attaching events to content loaded using Ajax. Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time (example Ajax).

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

Use Promise interface:

$.ajax({ ... }).then(successHandler, failureHandler);
     
    // OR
    var jqxhr = $.ajax({ ... });
    jqxhr.done(successHandler);
    jqxhr.fail(failureHandler);

Sample Ajax Template:

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);

Effects and Animations

Adopt a restrained and consistent approach to implementing animation functionality.
    DO NOT over-do the animation effects until driven by the UX requirements.
        Try to use simeple show/hide, toggle and slideUp/slideDown functionality to toggle elements.
        Try to use predefined animations durations of "slow", "fast" or 400 (for medium).

Plugins

Always choose a plugin with good support, documentation, testing and community support.
    Check the compatibility of plugin with the version of jQuery that you are using.
    Any common reusable component should be implemented as a jQuery plugin.  for jQuery Plugin Boilerplate code.

Chaining

Use chaining as an alternative to variable caching and multiple selector calls.

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

Whenever the chain grows over 3 links or gets complicated because of event assignment, use appropriate line breaks and indentation to make the code readable.

$("#myLink")
        .addClass("bold")
        .on("click", myClickHandler)
        .on("mouseover", myMouseOverHandler)
        .show();

For long chains it is acceptable to cache intermediate objects in a variable.

Miscellaneous

Use Object literals for parameters.

$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"
    });

Do not mix CSS with jQuery.

$("#mydiv").css({‘color‘:red, ‘font-weight‘:‘bold‘}); // BAD

.error { color: red; font-weight: bold; } /* GOOD */

$("#mydiv").addClass("error"); // GOOD

DO NOT use Deprecated Methods. It is always important to keep an eye on deprecated methods for each new version and try avoid using them.  for a list of deprecated methods.
    Combine jQuery with native JavaScript when needed. See the performance difference for the example given below:

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

来源于:http://lab.abhinayrathore.com/jquery-standards/

时间: 2025-01-08 01:50:32

jquery 编程的最佳实践的相关文章

jQuery编程的最佳实践

好像是feedly订阅里看到的文章,读完后觉得非常不错,译之备用,多看受益. 加载jQuery 1.坚持使用CDN来加载jQuery,这种别人服务器免费帮你托管文件的便宜干嘛不占呢.点击查看使用CDN的好处,点此查看一些主流的jQuery CDN地址. XHTML 1 2 3 <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js&qu

python高级编程之最佳实践,描述符与属性01

# -*- coding: utf-8 -*- # python:2.x __author__ = 'Administrator' #最佳实践 """ 为了避免前面所有的问题,必须考虑到几下几点: ~1:应该避免多重继承,可以一些设计模式来代替它 ~2:super使用必须一致,在类层次结构中,应该在所有地方都使用super或者彻底不使用它,滥用super和传统调用是一种滥用方法,建议使用super ~3:不要滥用经典类和新式类,两者都具备代码库将导致不同的mro表现 ~4:调

android学习二十四(网络编程的最佳实践)

前面的博客已经讲解了HttpURLConnection和HttpClient的用法,知道了如何发起HTTP请求,以及解析服务器返回 的数据.但是可能你发现了,因为一个应用程序很多地方都可能使用网络功能,而发送HTTP请求的代码基本相同,如果每次我们都去编写一遍发送HTTP请求的代码,这显然不太好. 通常情况下我们都应该将这些通用的网络操作提取到一个公共的类里,并提供一个静态方法,当想要发起网络请求的时候只需简单地调用一下这个方法即可.比如下面的写法: package com.jack.netwo

Android学习之基础知识十三—网络编程的最佳实践

上一讲已经掌握了HttpURLConnection和OkHttp的用法,知道如何发起HTTP请求,以及解析服务器返回的数据,但是也许你还没发现,之前我们的写法其实是很有问题的,因为一个应用程序很可能会在许多地方使用到网络功能,而发送HTTP请求的代码基本都是相同的,如果我们每次都去编写一遍发送HTTP请求的代码,这显然是非常差劲的做法. 通常情况下我们都应该将这些通用的网络操作提取到一个公共的类里,并提供一个静态方法,当想要发起网络请求的时候,只需要简单的调用一下这个方法即可,比如使用如下的写法

Javascript模块化编程(一)模块的写法最佳实践六、输入全局变量 独立性是模块的重要特点,模块内部最好不与程序的其他部分直接交互。 为了在模块内部调用全局变量,必须显式地将其他变量输入模块。

Javascript模块化编程,已经成为一个迫切的需求.理想情况下,开发者只需要实现核心的业务逻辑,其他都可以加载别人已经写好的模块但是,Javascript不是一种模块化编程语言,它不支持类class,更遑论模块module了 随着网站逐渐变成"互联网应用程序",嵌入网页的Javascript代码越来越庞大,越来越复杂.网页越来越像桌面程序,需要一个团队分工协作.进度管理.单元测试等等......开发者不得不使用软件工程的方法,管理网页的业务逻辑. Javascript模块化编程,已

jQuery的编码标准和最佳实践

加载jQuery 1.坚持使用CDN来加载jQuery,这种别人服务器免费帮你托管文件的便宜干嘛不占呢.点击查看使用CDN的好处,点此查看一些主流的jQuery CDN地址. <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script>window.jQuery

JS编程最佳实践

最近花了一周时间把<编写可维护的js> 阅读了一遍, 现将全书提到的JS编程最佳实践总结如下, 已追来者! 1.return 之后不可直接换行, 否则会导致ASI(自动分号插入机制)会在return 后插入一个分号. 2.一行语句最多不超过80个字符, 如果超过则应该在运算符后换行,并且追加两个缩进. 3.采用驼峰式命名,变量前缀为名词如:myName 函数应该以动词开始如:getName,常量应该以大写字母命名,如:MAX_COUNT, 构造函数首字母大写. 4.数字的写法: 整数:coun

Java 编程中关于异常处理的 10 个最佳实践

异常处理是书写 强健 Java应用的一个重要部分.它是关乎每个应用的一个非功能性需求,是为了优雅的处理任何错误状况,比如资源不可访问,非法输入,空输入等等.Java提供了几个异常处理特性,以try,catch和finally 关键字的形式内建于语言自身之中.Java编程语言也允许你创建新的异常,并通过使用  throw 和 throws关键字抛出它们.事实上,异常处理不仅仅是知道语法.书写一个强健的代码更多的是一门艺术而不仅仅是一门科学,这里我们将讨论一些关于异常处理的Java最佳实践.这些 J

jQuery编码规范与最佳实践

p{text-indent:2em;}前端开发whqet,csdn,王海庆,whqet,前端开发专家 翻译自:http://lab.abhinayrathore.com/ 翻译人员:前端开发whqet,意译为主,不当之处欢迎大家指正. 译者说:临近期末,大部分的基础教学内容已经讲解完毕,在进行比较大型的项目训练之前,如果能让学生了解甚至遵循一些前端开发的编码规范将会是一件非常有意义的事情.因此,本博客准备于近期整理一个编码规范与最佳实践的系列文章,包括html.css.javascript.jq