Home  >  Article  >  Web Front-end  >  Detailed explanation of best practices for advanced programming in jquery_jquery

Detailed explanation of best practices for advanced programming in jquery_jquery

WBOY
WBOYOriginal
2016-05-16 16:54:371105browse

Loading jQuery

1. Insist on using CDN to load jQuery. Why not take advantage of other people’s servers to host your files for free? Click to view the benefits of using CDN, and click here to view some mainstream jQuery CDN addresses.

Copy code The code is as follows:


<script>window.jQuery || document.write('&lt ;script src="js/jquery-1.11.0.min.js" type="text/javascript"></script>')

2. For security reasons, it is best to provide a local backup so that the website can work even when jQuery cannot be obtained from the remote CDN server, as shown in the above code. See details here.

3. Use the naked protocol URL (that is, remove http: or https:), as shown in the above code.

4. If possible, try to put your JavaScript and jQuery code at the bottom of the page. Click here for details, or view a standard HTML5 page template.

5. Which version should I use?

If you want to be compatible with IE678, please use version 2.x
For the lucky few who don’t need to consider compatibility, it is highly recommended to use the latest version of jQuery
When loading jQuery from a CDN server, it is best Write the full version (such as 1.11.0 instead of 1.11 or write 1 directly)
Never load it repeatedly
6. If you also use other JS frameworks such as Prototype, MooTools, Zepto Yunyun, because they The $ sign is also used, so you are no longer using the dollar sign for jQuery encoding, and use 'jQuery' instead. And calling $.noConflict() ensures that no conflicts will occur.

7. To check whether the browser supports some new features, please use Modernizr. Interstitial advertising: On the issue of not detecting browsers

About variables

1. It is best to add a $ prefix to jQuery type variables.

2. Always store the content returned by the jQuery selector into a variable for reuse

Copy the code The code is as follows:

var $products = $("div.products"); // Slow
var $products = $(".products"); // Fast

3. Use camel case naming

About selectors

1. Try to use ID selector. The mechanism behind it is actually to call the native document.getElementById(), so it is faster than other selectors.

2. Specify the type of element when using a class selector. If you don’t believe me, look at this performance comparison

Copy the code The code is as follows:

var $products = $( "div.products"); // Slow
var $products = $(".products"); // Fast

3. To find child elements under the ID parent container, please use the .find() method. The reason this is fast is that selecting elements by id does not use the Sizzle engine. See here for details

4. In multi-level search, the right side should be as detailed as possible and the left side should be as simple as possible. Learn more

Copy code The code is as follows:

// Ugly
$(" div.data .gonzalez");
// After optimization
$(".data td.gonzalez");

5. Avoid redundancy. Details or view performance comparison

Copy code The code is as follows:

$(".data table. attendees td.gonzalez");

// Good way: remove the redundancy in the middle
$(".data td.gonzalez");

6. Specify the context of selection.

Copy code The code is as follows:

// Poor code: because it needs to traverse the entire DOM to Find .class
$('.class');
// Gaopin code: Because you only need to search within the specified container range
$('.class', '#class-container') ;

7. The table uses a universal selector. View the detailed explanation

Copy the code The code is as follows:

$('div.container > * '); // Difference
$('div.container').children(); // Stick

8. Be wary of implicit universal selectors. If omitted, the * wildcard character is actually used. More information

Copy code The code is as follows:

$('div.someclass :radio' ); // Bad
$('div.someclass input:radio'); // Great

9.ID already represents uniqueness, and document.getElementById() is used behind it, so the table is mixed with other selectors.

Copy code The code is as follows:

$('#outer #inner'); // Dirty
$('div#inner'); // Messy
$('.outer-container #inner'); // Bad
$('#inner'); // Clean and tidy, In the background, just call document.getElementById()

DOM operation related

1. Uninstall any element from the document before operating it, and then paste it back again. This matter can be more detailed

Copy code The code is as follows:

var $myList = $ ("#list-container > ul").detach();
//...A lot of processing of $myList
$myList.appendTo("#list-container");
2. Organize the HTML in the code and then paste it into the DOM at once. Specifically, performance comparison

// This is not good
var $myList = $("#list");
for(var i = 0; i < 10000; i ){
$myList.append("

  • " i "
  • ");
    }

    // That’s good
    var $myList = $("#list");
    var list = "";
    for(var i = 0; i < 10000; i ){
    list = "
  • " i "
  • ";
    }
    $myList .html(list);

    // But this is better
    var array = [];
    for(var i = 0; i < 10000; i ){
    array[ i] = "
  • " i "
  • ";
    }
    $myList.html(array.join(''));

    3. Don’t deal with non-existent elements. Details

    Copy code The code is as follows:

    // Unscrupulous practice: jQuery background is running After completing three functions, you will know that this element actually does not exist at all
    $("#nosuchthing").slideUp();
    // It should be like this
    var $mySelection = $("#nosuchthing") ;
    if ($mySelection.length) {
    $mySelection.slideUp();
    }

    Event related

    1. Only write one handler for the document ready event on a page. In this way, the code is clear and easy to debug, and it is easy to track the progress of the code.

    2. The table uses anonymous functions as event callbacks. Anonymous functions are difficult to debug, maintain, test and reuse. Maybe you want to be more serious, take a look here

    Copy the code The code is as follows:

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

    3. The callback for processing the document ready event also uses anonymous functions. Anonymous functions are difficult to debug, maintain, test and reuse: (

    Copy code The code is as follows:

    $(function(){ ... }); // Bad practice: This function cannot be used and test cases cannot be written for it

    // Good practice
    $(initPage); // Or $(document).ready(initPage);
    function initPage(){
    // Here you can initialize the program
    }

    4. Further, it is best
    to also put the ready event handler in an external file and introduce it to the page, and the code embedded in the page only needs to be called.

    Copy code The code is as follows:


    <script><br> // Initialize some necessary global variables<br> $(document).ready(initPage); // Or $(initPage);<br></script>

    5. There are tens of millions of JS codes written inline to HTML, which is a debugging nightmare! You should always use jQuery to bind the event itself, so that you can dynamically unbind it at any time.

    Copy code The code is as follows:

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

    6. If possible, try to use a namespace when binding event handlers, so that you can easily unbind without affecting other bindings.

    Copy code The code is as follows:

    $("#myLink").on("click .mySpecialClick", myEventHandler); // Not bad
    // After that, let’s unbind gracefully
    $("#myLink").unbind("click.mySpecialClick");

    Asynchronous operation

    1. Use $.ajax() directly instead of .getJson() or .get(), because jQuery still converts it to the former internally

    2. Use HTTP to initiate requests for HTTPS sites. It is best to simply specify it (remove HTTP or HTTPS from your URL)

    3. The table embeds parameters in the link, please use special parameter settings to pass

    Copy code The code is as follows:

    // Code that is not easy to read...
    $.ajax({
    url: "something.php?param1=test1¶m2=test2",
    ....
    });

    // Easier to read...
    $.ajax({
    url: "something.php",
    data: { param1: test1, param2: test2 }
    });

    4. Try to specify the data type so that you know what kind of data you want to process (see the Ajax template mentioned below)

    5. For asynchronously dynamically loaded content, it is best to use a proxy to bind event handlers. The advantage of this is that it is also valid for element events that are dynamically loaded later. You may want to know more

    Copy code The code is as follows:

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

    6. Use Promise mode. More examples

    Copy code The code is as follows:

    $.ajax({ ... } ).then(successHandler, failureHandler);

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

    7. One point for standard Ajax template. Chasing the root cause

    Copy code The code is as follows:

    var jqxhr = $.ajax({
    url: url,
    type: "GET", // The default is GET, you can change it as needed
    cache: true, // The default is true, but for script, the jsonp type is false, you can set it yourself
    data: {}, // Put the request parameters here.
    dataType: "json", // Specify the desired data type
    jsonp: "callback", // Specify the callback to process the JSONP type Request
    statusCode: { // If you want to handle errors in each status
    404: handler404,
    500: handler500
    }
    });
    jqxhr.done(successHandler) ;
    jqxhr.fail(failureHandler);

    Animation and special effects

    1. Maintain a consistent and unified animation implementation

    2. Follow the user experience closely and avoid abusing animation special effects

    Use simple show-hide, state switching, slide-in and slide-out effects to display elements
    Use preset values ​​to set the animation speed to 'fast', 'slow', or 400 (medium speed)
    Plug-in related

    1. Always choose a plugin that has good support, good documentation, thorough testing and an active community

    2. Pay attention to whether the plug-in used is compatible with the jQuery version currently used

    3. Some common functions should be written as jQuery plug-ins. One minute jQuery plug-in writing template

    Chain syntax

    1. In addition to using variables to save the results returned by the jQuery selector, you can also make good use of chain calls.

    Copy code The code is as follows:

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

    2. When there are more than 3 chain calls or the code is slightly complicated due to bound callbacks, use line breaks and appropriate indentation to improve the readability of the code.

    Copy code The code is as follows:

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

    3. For particularly long calls, it is best to use variables to save intermediate results to simplify the code.

    Others

    1. Use object literals to pass parameters

    Copy code The code is as follows:

    $myLink.attr("href", "#").attr("title", "my link").attr("rel", "external"); // Oops: attr was called three times
    // Yes, attr
    $myLink.attr({
    href: "#",
    title: "my link",
    rel: "external"
    });

    2. Mix CSS and jQuery

    Copy the code The code is as follows:

    $("#mydiv").css({'color':red, 'font-weight':'bold'}); // Bad
    .error {/* Good*/
    color: red ;
    font-weight: bold;
    }
    $("#mydiv").addClass("error");

    3. Always pay attention to the official Changelog and use the abandoned method.

    4. Use native JavaScript when appropriate.

    Copy code The code is as follows:

    $("#myId"); // How much is still Will be inferior to...
    Statement:
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn