jquery performance optimization

1. Selection of selector

The performance of id selector is the best, followed by tag selector, class selector and attribute selector

2. Cache jquery objects

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

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


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>"

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

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

6. Use event agent to improve event performance


7. Custom plug-in reuse code

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

8 using join to splice strings

var array = new Array();
for(var i = 0;i <10;i++){

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>

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

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