jquery performance optimization

1. Selection of selector

The performance of id selector is the best, followed by tag selector, class selector and attribute selector
$("#id")>$("p")>$(".class")>$("[attribute=value]")

2. Cache jquery objects

var $active_light = $("#trafic_light input");//Cache variables
$active_light.bind("click",function(){});
$active_light.css("border","1px dashed yellow");
//Add chain syntax to simplify code
$active_light.bind().css().fadeIn();

3. Plan to use jquery object in other variables and cache it into global object

window.$my={
    head:$("head"),
    traffic_light:$("#traffic_light"),
    traffix_button:$("#trafic_button")
};
$my.head.append("script");

4. Reduce the deletion and modification of dom nodes when traversing dom elements to improve performance

var list =[],$mylist = $("#mylist"),li="";
for(var i =0;i < list.length;i++){
    li +="<li>"+i+"</li>"
}
$mylist.html(li);

5. Use for loop or while loop instead of $. each() performance

var array = new Array();
for(var i = 0;i <array.length;i++){
    array[i]=i;
}

6. Use event agent to improve event performance

$('#myTable').on('click','td',function(){
    $(this).css('background','red');
});

7. Custom plug-in reuse code

(function($){
    $.fn.yourPluginName = function(){
        //Add your own code
        return this;
    }
})(jQuery);

8 using join to splice strings

var array = new Array();
for(var i = 0;i <10;i++){
    array[i]=i;
}
$("#list").html(array.join(''));

Using the data attribute of html reasonably can help us to insert data, especially the data exchange between the front and back end

<div id="d1" data-role="page" data-last-value="43" data-options='{"name":"John"}'></div>
$("#d1").data("role");
$("#d1").data("lastValue");
#("#d1").data("options").name;

10. Try to use native js methods to reduce function calls

//such as var $cr = $("#cr"); $cr.is(":checked");
var cr = $("#cr").get(0); cr.checked
$(this).css("color","red");
this.style.color="red";

11. Compress js code
Full + compressed
Use Gzip to compress, remove the comment of js code, blank, and compress the variable length

Tags: Attribute JQuery

Posted on Wed, 06 May 2020 09:14:15 -0700 by carlmcdade