Best practices for advanced jquery programming

  • 2020-03-30 02:28:07
  • OfStack

To load the jQuery

1. Stick to using CDN to load jQuery. Why not take advantage of someone else's server hosting your files for free? Click here to see the benefits of using CDN and see some of the mainstream jQuery CDN addresses.


<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/jquery-1.11.0.min.js" type="text/javascript"></script>')</script>

2. To be safe, it is best to provide a local backup so that the site works if jQuery cannot be obtained from a remote CDN server, as shown in the code above. See details here.

3. Use naked protocol urls (that is, remove HTTP: or HTTPS:), as shown in the code above.

4. If possible, place your JavaScript and jQuery code at the bottom of the page. Go here, or look at a standard template for an HTML5 page.

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 have to worry about compatibility, the latest version of jQuery is highly recommended
When loading jQuery from a CDN server, it is best to write the full version (such as 1.11.0 instead of 1.11 or write a 1)
Never reload
6. If you also use other JS frameworks such as Prototype, MooTools, Zepto, etc., because they also use the $symbol, you will use the dollar sharp symbol to code jQuery, and use 'jQuery' instead. And it calls $.noconflict () to ensure that noConflict occurs.

About the variable

1. It is best to prefix variables of type jQuery with $.

2. Always store the contents returned by jQuery selectors in variables for reuse


var $products = $("div.products"); //  slow 
var $products = $(".products"); //  fast 

Name it hump

About selectors

1. Try to ID selector. The mechanism behind this is to call the native document.getelementbyid (), which is faster than other selectors.

2. The table specifies the type of element when using the class selector. Look at this performance comparison
The same code at the page code block index 1

Use the.find() method to find child elements under the ID parent container. The reason this is fast is that selecting elements by id does not use the Sizzle engine. See more here

4. In multilevel lookups, specify as much detail on the right as possible and as little detail on the left as possible. To learn more


//  ugly 
$("div.data .gonzalez");
//The optimized
$(".data td.gonzalez");

Avoid redundancy. See details or performance comparisons


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

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

6. Specify the selected context.


//Bad code: because you need to traverse the entire DOM to find.class
$('.class');
//High quality code: because only in the specified container scope to find
$('.class', '#class-container');

7. Table using universal selector. See the explanation


$('div.container > *'); //  poor 
$('div.container').children(); //  rod 

8. Beware of implicit universal selectors. In the case of ellipsis, the * wildcard is actually used. For more information


$('div.someclass :radio'); //  poor 
$('div.someclass input:radio'); //  rod 

9.ID is already unique, and document.getelementbyid () is used behind it, so the table is a mashup of other selectors.


$('#outer #inner'); //  dirty 
$('div#inner'); //  The disorderly 
$('.outer-container #inner'); //  poor 
$('#inner'); //Clean, just call document.getelementbyid () in the background

DOM manipulation correlation

1. Uninstall any element from the document before manipulating it, and then post it back. There's more to this


var $myList = $("#list-container > ul").detach();
//. A bunch of processing on $myList
$myList.appendTo("#list-container");
2. The code will be HTML Post it again once it's organized DOM . Specifically, performance comparisons 
//This is bad
var $myList = $("#list");
for(var i = 0; i < 10000; i++){
    $myList.append("<li>"+i+"</li>");
}

//That's good
var $myList = $("#list");
var list = "";
for(var i = 0; i < 10000; i++){
    list += "<li>"+i+"</li>";
}
$myList.html(list);

//But it's better this way
var array = []; 
for(var i = 0; i < 10000; i++){
    array[i] = "<li>"+i+"</li>"; 
}
$myList.html(array.join(''));

Don't deal with nonexistent elements. details


//Unconscionable: you don't know that this element doesn't exist until you've run through three functions in jQuery
$("#nosuchthing").slideUp();
//Should be like this
var $mySelection = $("#nosuchthing");
if ($mySelection.length) {
    $mySelection.slideUp();
}

Event correlation

1. Only one handler for the document ready event is written on a page. In this way, the code can be easily debugged and the progress of the code can be easily tracked.

2. The table USES anonymous functions to make callbacks to events. Anonymous functions are difficult to debug, maintain, test and reuse. Maybe you want to be serious, check this out


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

3. Handle the callback of the document ready event with anonymous function, which is not easy to debug, maintain, test and reuse


$(function(){ ... }); //Bad practice: you can't take advantage of this function or write a test case for it

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

Step forward, preferably
It also introduces the handler for the ready event into the page in an external file, where the embedded code is simply called.


<script src="my-document-ready.js"></script>
<script>
 //Start with the necessary global variables
 $(document).ready(initPage); //Or $(initPage);
</script>

5. Millions of tables to write inline HTML JS code, this is a debugging nightmare! You should always use jQuery to bind event byproducts so that you can unbind them dynamically at any time.


<a id="myLink" href="#" onclick="myEventHandler();">my link</a> <!-- bad  -->
$("#myLink").on("click", myEventHandler); // GOOD

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


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

Asynchronous operations

1. Directly use $.ajax() and use.getjson () or.get(), because jQuery internally converts it to the former

2. The table USES HTTP to make requests for HTTPS sites, preferably just the table (remove HTTP or HTTPS from your URL)

3. The table contains parameters in the link, please use special parameter Settings to pass


//Unreadable code...
$.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 type of data so you know what you're dealing with (see the Ajax template below)

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


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

Use the Promise model. More examples


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

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

7. One cent for standard Ajax templates. Search for root cause


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

Animation and special effects

1. Maintain a consistent and unified animation implementation

2. Follow user experience closely and abuse animation effects

Use simple hide, state switch, 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

2. Note whether the plug-in is compatible with the current jQuery version

3. Some common functions should be written as jQuery plug-ins. A jQuery plug-in authoring template

Chain syntax

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


var $products = $("div.products"); //  slow 
var $products = $(".products"); //  fast 
0

2. Use line breaks and proper indentation to improve code readability when chain calls are made more than 3 times or when code is slightly complex due to binding callbacks.


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

3. For extremely long calls, it's best to save intermediate results in variables to simplify the code.

other

1. Use object literals to pass arguments


$myLink.attr("href", "#").attr("title", "my link").attr("rel", "external"); //Bad: three attr calls
//Yes, only one attr is called
$myLink.attr({
    href: "#",
    title: "my link",
    rel: "external"
});

2. The table will mix CSS with jQuery


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

3. Keep an eye on the official Changelog and use the abandoned method.

4. Use native JavaScript when appropriate.


$("#myId"); //It will still be less than...


Related articles: