Twelve lessons in writing high-quality jQuery code

Posted by cbailster on Sat, 18 May 2019 02:31:41 +0200

1. Reference jQuery correctly
  1. Try to introduce jQuery before the end of the body, not in the head.
  2. Introduce jQuery with a third-party CDN, and be aware that when problems arise with using a third-party CDN, local jQuery files should be introduced.
  3. If a script file is introduced before </body>, you do not need to write document.read because the DOM is already loaded when the js code is executed.
<body>  
    <script src="//lib.sinaapp.com/js/jquery11/1.8/jquery.min.js"></script>  
    <script>window.jQuery  document.write('<script src="jquery1.8.min.js">\x3C/script>')</script>  
</body> 
2. Optimize jQuery selector

Effective and correct use of jQuery selectors is the basis for skilled use of jQuery, and mastering jQuery selectors takes some time to accumulate, so we should pay attention to the use of selectors when starting to learn jQuery.

<div id="nav" class="nav">  
    <a class="home" href="http://www.jquery001.com">jQuery Learning Network</a>  
    <a class="articles" href="http://www.jquery001.com/articles/">jQuery Course</a>  
</div>

If we choose the a element whose class is home, we can use the following code:

$('.home');  //1  
$('#nav a.home');  //2  
$('#nav').find('a.home');  //3 

Method 1, which causes jQuery to find a class-home element in the entire DOM, has conceivable performance.
Method 2 adds a context to the element to find, where it becomes a child element whose search id is nav, which greatly improves the search performance.
Method 3, which uses the find method, is faster, so method 3 is the best.
With regard to the performance priority of the jQuery selector, the ID selector is faster than the element selector and the element selector is faster than the class selector.Because the ID selector and element selector are native JavaScript operations, and the class selector is not, you can then see the difference between find context and find() children.

2.1. Some rules

  • The CSS parsing engine calculates each rule from right to left, starting with the key selectors, counting each selector from right to left until a matching selector is found, and discarding the search if no matching selector is found.
  • Using lower-level rules is often more efficient.
  • The most specific selector possible - ID is better than tag.
  • Avoid unnecessary redundancy.

In general, keep selectors simple (such as making full use of ID selectors), and be as specific as possible with key selectors, which can add speed to your site, whether for JavaScript or CSS.So far, no matter which browser you use, using the ID selector or when the class selector is the fastest way to select elements.

2.2, Avoid multiple ID selectors

Id selectors should be unique, so there is no need to add additional selectors.

// Too bad
$('div#myid');
$('div#footer a.myLink');
// proposal
$('#myid');
$('#footer .myLink');

It is emphasized here that ID selectors should be unique, do not need to add additional selectors, and do not need multiple descendant ID selectors.

// Too bad
$('#outer #inner');
// proposal
$('#inner');

2.3. Avoid implicit universal selectors

Universal selectors are sometimes implicit and not easy to discover.

// Too bad
$('.someclass :radio');
// proposal
$('.someclass input:radio');

2.4, Avoid generic selectors

Putting a generic selector in a descendant selector can be very poor.

// Too bad
$('.container > *');
// proposal
$('.container').children();

2.5, Choose Shortcuts

One way to streamline your code is to take advantage of coding shortcuts.

// Too bad
if(collection.length > 0){..}
// proposal
if(collection.length){..}

2.6. Specify context for selector

By default, when a selector is passed to jQuery, it traverses the entire DOM, and the jQuery method has an underutilized parameter that either passes a context parameter into jQuery to limit it to searching only a specific part of the DOM.

//Bad, it traverses the entire DOM
$(".class");
//Suggested, only search for #id elements
$(".class","#id");

Performance comparison of jQuery selectors:

$(".class","#id") > $("#id .class") > $(".class")
3. Caching jQuery objects

Caching jQuery objects reduces unnecessary DOM lookups, so you can refer to caching jQuery objects to improve performance.

// Too bad
h = $('#element').height();
$('#element').css('height',h-20);
// proposal
$element = $('#element');
h = $element.height();
$element.css('height',h-20);

3.1. Parent element using subquery cache

As mentioned earlier, DOM traversal is an expensive operation.Typically, parent elements are cached and reused when child elements are selected.

// Too bad
var
    $container = $('#container'),
    $containerLi = $('#container li'),
    $containerLiSpan = $('#container li span');
// Suggestions (Efficient)
var
    $container = $('#container '),
    $containerLi = $container.find('li'),
    $containerLiSpan= $containerLi.find('span');
4. Variables

4.1, Avoid global variables

jQuery, like javascript, is generally best to ensure that your variables are within the scope of the function.

// Too bad
$element = $('#element');
h = $element.height();
$element.css('height',h-20);
// proposal
var $element = $('#element');
var h = $element.height();
$element.css('height',h-20);

4.2. Use Hungarian nomenclature

Prefixing variables with a $prefix makes it easy to identify jQuery objects.

// Too bad
var first = $('#first');
var second = $('#second');
var value = $first.val();
// Recommendation - prefix jQuery objects with $
var $first = $('#first');
var $second = $('#second'),
var value = $first.val();

4.3. Use var chains (single var mode)

Combining multiple var statements into one statement, I recommend placing unassigned variables after them.

var $first = $('#first'),
      $second = $('#second'),
      value = $first.val(),
      k = 3,
      cookiestring = 'SOMECOOKIESPLEASE',
      i,
      j,
      myArray = {};
5. Use event delegation correctly

In the new version of jQuery, shorter on ("click") is used to replace functions like click().In previous versions, on () was bind().Since jQuery version 1.7, on () attaches the preferred method of event handler.However, for consistency reasons, you can simply use the on() method in its entirety.

<table id="t">  
    <tr>  
        <td>I am a cell</td>  
    </tr>  
</table>  

For example, if we want to bind a click event to the cell above, an unnoticed friend may write as follows:

$('#t').find('td').on('click', function () {  
    $(this).css({ 'color': 'red', 'background': 'yellow' });  
});

This binds events to each td, and in a test that binds click events to 100 cells, they differ by as much as seven times in performance. A good practice is to write the following:

$('#t').on('click', 'td', function () {  
    $(this).css({ 'color': 'red', 'background': 'yellow' });  
}); 
6. Streamline jQuery code

As in the above code, we have merged jQuery code appropriately, similar to the.attr() method, which we have not written below:

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

6.1. Merge function

In general, it is best to combine functions whenever possible.

// Too bad
$first.click(function(){
    $first.css('border','1px solid red');
    $first.css('color','blue');
});
// proposal
$first.on('click',function(){
    $first.css({
        'border':'1px solid red',
        'color':'blue'
    });
});

6.2. Chain operation

The chain operation of the jQuery implementation method is very easy.Take advantage of this below.

// Too bad
$second.html(value);
$second.on('click',function(){
    alert('hello everybody');
});
$second.fadeIn('slow');
$second.animate({height:'120px'},500);
// proposal
$second.html(value);
$second.on('click',function(){
    alert('hello everybody');
}).fadeIn('slow').animate({height:'120px'},500);
7. Reduce DOM operations

The DOM may be frequently manipulated when you first start using jQuery, which can be quite performance intensive.If we want to dynamically output a table in the body, some friends will write as follows:

//Too bad
var $t = $('body');  
$t.append('<table>');  
$t.append('<tr><td>1</td></tr>');  
$t.append('</table>');
//proposal
$('body').append('<table><tr><td>1</td></tr></table>');

This adds the table string to the body after splicing it, and the DOM operation only needs one time.Previous friends in the group had problems with IE output because of this, and the fastest way to create strings for string stitching can be referred to.

7.1. Separating elements in heavy operations

If you plan to do a lot with DOM elements (set multiple attributes or css styles consecutively), it is recommended that you first separate the elements and then add them.

// Too bad
var
    $container = $("#container"),
    $containerLi = $("#container li"),
    $element = null;
$element = $containerLi.first();
//...many complicated operations
// better
var
    $container = $("#container"),
    $containerLi = $container.find("li"),
    $element = null;
$element = $containerLi.first().detach();
//...many complicated operations
$container.append($element);

7.2, Minimize DOM updates

Relayout and redraw are the two most common and expensive operations on WEB pages.

  • Redraws occur when styles are changed without changing the geometric layout of the page.Hiding an element or changing its background color will result in a redraw.
  • When the page structure is updated, it will cause the page to be re-laid out.
    //Too bad
    for(var i=0; i<10000; i++){
    $("#main table").append("<tr><td>aaaa</td></tr>");
    }
    //proposal
    var tablerow = "";
    for(var i=0; i<10000; i++){
    tablerow  += "<tr><td>aaaa</td></tr>";
    }
    $("#main table").append(tablerow);
8. Maintain code readability

As you streamline your code and use chains, it can be difficult to read.Adding compaction and line breaks works well.

// Too bad
$second.html(value);
$second.on('click',function(){
    alert('hello everybody');
}).fadeIn('slow').animate({height:'120px'},500);
// proposal
$second.html(value);
$second
    .on('click',function(){ alert('hello everybody');})
    .fadeIn('slow')
    .animate({height:'120px'},500);
9. Select Short Circuit Evaluation

Short circuit evaluation is an expression that evaluates from left to right using the && (logical AND) or (logical OR) operators.

// Too bad
function initVar($myVar) {
    if(!$myVar) {
        $myVar = $('#selector');
    }
}
// proposal
function initVar($myVar) {
    $myVar = $myVar   $('#selector');
}
10. Keep up to date

New versions are usually better: lighter and more efficient.Obviously, you need to consider the compatibility of the code you want to support.For example, ie 6/7/8 is not supported in version 2.0.
Discard method
It is important to note the abandonment methods for each new version and try to avoid using them.

// Bad - live is obsolete
$('#stuff').live('click', function() {
  console.log('hooray');
});
// proposal
$('#stuff').on('click', function() {
  console.log('hooray');
});
// Note: This may be inappropriate, live should be able to achieve real-time binding, delegate may be more appropriate
11. Last Advice

Finally, the goal of this article is to improve jQuery performance and some other good suggestions.If you want to do more research on this topic, you will find it interesting.Remember, jQuery is not indispensable, it's just an option.Think about why you want to use it.DOM operation?ajax?Template?css animation?Or the selector engine?Perhaps a javascript mini-framework or a customized version of jQuery is a better choice.

Although it's all clichy, I find that I can't do all of the above very well and write down the hope that I can do all of them.

12. Do not use jQuery

Native functions are always the fastest, which is not difficult to understand. We should not forget native JS in code writing.
Let's summarize these first. Each suggestion is not difficult to understand, but it will take a lot of time to summarize it in a comprehensive way.For example, in reducing code snippets, you can use the $.grep() method if you need to get a new array from the array conditionally. If you have your own ideas when using jQuery, you are welcome to share them in the message!


Author: Dunizb
Link: http://www.imooc.com/article/10307#comment
Source: Mucho.com

Topics: JQuery Javascript IE network