jQuery Best Practices

Version specification

Since IE6/7/8 is no longer available after jQuery 2.0, most projects recommend the latest version of 1.X, which is based on 1.11.1.

Ready incident

Before DOM operation, it is necessary to monitor the page loading progress, and DOM editing operation should be performed after the page loading is completed.

    $(document).ready(function(){
        ...
    });

perhaps

    $(function(){
        ...
    });

selector

1. Prioritize the use of native methods var el = document.getElementById("element"); 2. Priority to use ID selector performance order: ID selector > label selector > class selector > attribute selector > pseudo-Class selector

    //Performance decreases from top to bottom
    $("#element")
    $("input")
    $(".element")
    $("[type=submit]")
    $(":hidden")

3. The ID selector (getElementsById), the tag selector (getElementsByTagName) all have native methods, so they are very fast. The class selector has native methods (getElementsByClassName) in mainstream browsers except IE6-8.

var foo = document.getElementById("foo");
var input = document.getElementsByTagName("input");
//IE6-8 does not support class selectors
var bar = document.getElementsByClassName("bar");

4. For element retrieval without id, the shortest path ancestor element ID is used as the default search range, and pure class selector or label selector is used.

Style sheet operations

When applying multiple styles to an object, the addClass/removeClass method should be used as far as possible to avoid multiple operations on the object.

var $element = $("#element");
$element.css("width","200px");
$element.css("height","300px");
$element.css("background","#fff");

/*Recommendations are as follows:*/
.on{
   width:200px;
   height:200px;
   background:#fff;
}
var $element = $("#element");
$element.addClass("on");

Selector save

If multiple operations are performed on the same element, it is recommended that the selector be cached or chained.

//Poor performance
$("#element").click(function(){ });
$("#element").empty();
$("#element").show();
//Recommended Writing (Caching)
var $element = $("#element");
$element.click(function(){ });
$element.empty();
$element.show();
//Recommended Writing (Chain)
$("#element").click(function(){
    //...
}).empty().show();

Event delegation

The event model of javascript adopts the "bubbling" mode, that is to say, the events of child elements will "bubbling" upward step by step and become the events of parent elements. When there are two situations, it is recommended to use time delegation to bind the same event for many elements in DOM, and to bind events for elements that do not yet exist in DOM.

//For example, if you have 100 td elements, this writing binds 100 click events
//Poor performance
$("td").click(function(){
    //...
});
//It's recommended that you bind events to table s only once
//Recommended writing method
$("table").on("click","td",function(){
    //...
});

event namespace

If possible, use a namespace when binding event handlers, which makes it easy to unbind without affecting other bindings.

//Event binding
$("#myLink").on("click.mySpecialClick", myEventHandler);
// Unbind
$("#myLink").off("click.mySpecialClick");

Merge DOM operations

Minimize or merge DOM operations.

//Poor performance
var i;
var $wrapper = $("#wrapper");
for(i = 0;i<100;i++){
    var html = "<div>"+i+"</div>";
    $wrapper.append(html);
}
//Recommended writing method
var i;
var $wrapper = $("#wrapper");
var html = "";
for(i = 0;i<100;i++){
    html += "<div>"+i+"</div>";
}
$wrapper.append(html);

JS native method

JQuery is not as fast as the native javascript method. So avoid using jQuery whenever native methods are available.

/*selector*/
//Poor performance
var id = $(this).attr("id");
//Recommended writing method
var id = this.id;
/*loop*/
//Poor performance
$.each(arr,function(){
    ...
});
//Recommended writing method
for(var i = 0;i<arr.length;i++){
    ...
}

ajax

The following is the standard ajax request template, which is recommended for event handling.

//ajax template
var successHandler = function(){
    //...
};
var failureHandler = function(){
    //...
};
var alwaysFunc = function(){
    //...
};
var jqxhr = $.ajax({
    url: url,
    type: "GET", // By default GET, you can change it as needed
    data: {}, // Put the request parameters here.
    dataType: "json", // Specify the desired data type
    statusCode: { // If you want to deal with state errors
        404: handler404,
        500: handler500
    }
});
jqxhr.done(successHandler);
jqxhr.fail(failureHandler);
jqxhr.always(alwaysFunc);

Keywords: JQuery Javascript Attribute JSON

Added by shikhartandon on Sun, 02 Jun 2019 00:21:01 +0300