Application of jQuery design idea

Time:2021-11-13

Transferred from: Ruan Yifeng August 4, 2011http://www.ruanyifeng.com/blo…

Last week, I cleaned uphttps://segmentfault.com/a/11…Understanding of jQuery design ideas.

That article is an introductory tutorial, which explains from the perspective of design ideas“How to use jquery“Today’s article goes further and explains”How to make good use of jquery“。

I mainly refer to Addy Osmani’s ppt jQuery proven performance tips and tricks. He is a member of the jQuery development team and has certain authority. His conclusions are supported by test data and are very valuable.

====================================================================================

JQuery best practices

Ruan Yifeng finishing

1. Use the latest version of jQuery

The version of jQuery is updated quickly. You should always use the latest version. Because the new version will improve performance, there are many new features.

Let’s take a look at the performance differences between different versions of jQuery. Here are the three most common jQuery selection statements:

    $('.elem')
  $('.elem', context)
  context.find('.elem')

Application of jQuery design idea
It can be seen that version 1.6.2 runs far more times than the two old versions. Especially the first statement, the performance has been improved several times.

The tests of other statements, such as. Attr (“value”) and. Val (), are also the new version of jQuery, which performs better than the old version.

2. Align the selector with the

In jQuery, you can use multiple selectors to select the same web page element. The performance of each selector is different, and you should understand their performance differences.

(1) The fastest selectors: ID selectors and element label selectors

For example, the following statements perform best:

    $('#id')
  $('form')
  $('input')

When encountering these selectors, jQuery will automatically call the browser’s native methods (such as getelementbyid ()), so their execution speed is fast.

(2) Slower selector: class selector

The performance of $(‘. Classname’) depends on different browsers.

Firefox, Safari, chrome and opera browsers all have the native method getelementsbyclassname (), so the speed is not slow. However, ie5-ie8 do not deploy this method, so this selector will be quite slow in ie.

(3) The slowest selectors: pseudo class selectors and property selectors

Let’s start with an example. To find all hidden elements in the web page, you need to use the pseudo class selector:

$(':hidden')

An example of an attribute selector is:

$('[attribute=value]')

These two statements are the slowest because browsers do not have native methods for them. However, the new versions of some browsers have added queryselector () and queryselectorall () methods, which will greatly improve the performance of such selectors.

Finally, it is the performance comparison diagram of different selectors.

Application of jQuery design idea

You can see that the ID selector is far ahead, then the label selector, and the third is the class selector. Other selectors are very slow.

3. Understand the relationship between child elements and parent elements

The following six selectors select child elements from parent elements. Do you know which is the fastest and which is the slowest?

  

    $('.child', $parent)
  $parent.find('.child')
  $parent.children('.child')
  $('#parent > .child')
  $('#parent .child')
  $('.child', $('#parent'))

Let’s look at it sentence by sentence.

(1)$(‘.child’, $parent)

The meaning of this statement is to give a DOM object and select a child element from it. JQuery will automatically convert this statement to $parent. Find (‘. Child’), which will cause some performance loss. It is 5% – 10% slower than the fastest form.

(2)$parent.find(‘.child’)

This is the fastest statement The find () method will call the browser’s native methods (getelementbyid, getelementbyname, getelementbytagname, etc.), so it is faster.

(3)$parent.children(‘.child’)

Inside jQuery, this statement will use $. Sibling () and JavaScript’s nextsibling () methods to traverse nodes one by one. It is about 50% slower than the fastest form.

(4)$(‘#parent > .child’)

JQuery uses sizzle engine internally to handle various selectors. The selection order of the sizzle engine is from right to left, so this statement selects. Child first, and then filters out the parent elements #parent one by one, which makes it about 70% slower than the fastest form.

(5)$(‘#parent .child’)

This statement is the same as the previous one. However, the previous one only selects direct sub elements, and this one can select multi-level sub elements, so its speed is slower, about 77% slower than the fastest form.

(6)$(‘.child’, $(‘#parent’))

Query will convert this statement into $(‘#parent’). Find (‘. Child’), which is 23% slower than the fastest form.

Therefore, the best choice is $parent. Find (‘. Child’). Moreover, because $parent is often generated in the previous operation, jQuery will cache it, which further speeds up the execution speed.

For specific examples and comparison results, please seehere

4. Don’t overuse jQuery

JQuery is no faster than native JavaScript methods. Therefore, when there are native methods that can be used, try to avoid using jQuery.

Taking the simplest selector as an example, document. Getelementbyid (“foo”) is more than 10 times faster than $(“#foo”).

Let’s take another example. Bind a function to handle click events for element a:

  

    $('a').click(function(){
    alert($(this).attr('id'));
  });

This code means that after clicking the a element, the ID attribute of the element will pop up. To get this attribute, you must call jQuery twice in a row, the first time is $(this) and the second time is attr (‘id ‘).

In fact, this treatment is completely unnecessary. The more correct way is to directly use the JavaScript native method and call this.id:

  

    $('a').click(function(){
    alert(this.id);
  });

According to the test, this. ID is more than 20 times faster than $(this). Attr (‘id ‘).

5. Cache

Selecting a web page element is an expensive step. Therefore, you should use the selector as few times as possible, and cache the selected results as much as possible for reuse in the future.

For example, the following is a bad way to write:

  

    jQuery('#top').find('p.classA');
  jQuery('#top').find('p.classB');

A better way to write it is:

  

    var cached = jQuery('#top');
  cached.find('p.classA');
  cached.find('p.classB');

According to the test, caching is 2-3 times faster than not caching.

6. Use chain writing

A major feature of jQuery is that it allows chaining.
  

$('div').find('h3').eq(2).html('Hello');

When using chained writing, jQuery automatically caches the results of each step, so it is faster than non chained writing. According to the test, chained writing is about 25% faster than non chained writing (without cache).

7. Event delegation

The event model of JavaScript adopts the “bubbling” mode, that is, the events of the child element will “bubble” up level by level and become the events of the parent element.

Using this, the binding of events can be greatly simplified. For example, there is a table (table element) with 100 grids (TD element). Now it is required to bind a click event on each grid. Do you need to execute the following command 100 times?

  

    $("td").on("click", function(){
    $(this).toggleClass("click");
  });

The answer is no, we just need to bind this event to the table element, because after the click event of TD element, this event will “bubble” on the parent element table and be monitored.

Therefore, this event only needs to be bound once on the parent element instead of 100 times on the child element, which greatly improves the performance. This is called “delegate processing” of an event, that is, the child element “delegates” the parent element to process the event.

  

    $("table").on("click", "td", function(){
    $(this).toggleClass("click");
  });

A better way is to bind the event to the document object.

  

    $(document).on("click", "td", function(){
    $(this).toggleClass("click");
  });

If you want to unbind the event, use the off () method.

  

$(document).off("click", "td");

8. Change the DOM structure less

(1) Changing the DOM structure is expensive, so don’t use methods such as. Append(),. Insertbefore() and. Insetafter() frequently.

If you want to insert multiple elements, merge them first, and then insert them at one time. According to the test, the merge insert is nearly 10 times faster than the non merge insert.

(2) If you want to do a lot of processing on a DOM element, you should first take the element out of the DOM with the. Detach () method, and then insert it back into the document after processing. According to the test, using the. Detach () method is 60% faster than not using it.

(3) If you want to store data on a DOM element, don’t write it as follows:

  

    var elem = $('#elem');
  elem.data(key,value);

But to write

  

    var elem = $('#elem');
  $.data(elem[0],key,value);

According to the test, the latter writing method is nearly 10 times faster than the former. Because the elem. Data () method is defined on the prototype object of the jQuery function, and the $. Data () method is defined on the jQuery function. When calling, it is not called from the complex jQuery object, so the speed is much faster. (see point 10 below.)

(4) When inserting HTML code, the browser’s native innterhtml () method is faster than the HTML () method of jQuery object.

9. Properly handle the cycle

Loop is always a time-consuming operation. If you can use a complex selector to directly select elements, you don’t use loop to identify elements one by one.

The JavaScript native loop methods for and while are faster than the. Each () method of jQuery, and the native method should be used first.

10. Generate jQuery objects as few as possible

Whenever you use a selector (such as $(‘#id’)), a jQuery object is generated. JQuery object is a huge object with many properties and methods, which will occupy a lot of resources. Therefore, try to generate as few jQuery objects as possible.

For example, many jQuery methods have two versions, one for jQuery objects and the other for jQuery functions. The following two examples take out the text of an element and use the text () method.

You can either use the version for jQuery objects:

  

    var $text = $("#text");
  var $ts = $text.text();

You can also use the version for the jQuery function:

  

    var $text = $("#text");
  var $ts = $.text($text);

Because the latter version of jQuery function does not operate through jQuery objects, it has less overhead and faster speed.

11. Select the method with the shortest scope chain

Strictly speaking, this principle applies to all JavaScript programming, not just jQuery.

As we know, JavaScript variables use chained scopes. When reading a variable, first look for the variable in the current scope. If it cannot be found, go to the scope of the previous layer to look for the variable. This design makes it much faster to read local variables than global variables.

See the following two codes. The first code reads global variables:

  

    var a = 0;
  function x(){
    a += 1;
  }

The second code is to read local variables:

  

    function y(){
    var a = 0;
    a += 1;
  }

When the second code reads variable a, it does not need to go to the upper scope, so it is five or six times faster than the first code.

Similarly, when calling object methods, the closure mode is faster than the prototype mode.

Prototype mode:

  

    var X = function(name){ this.name = name; }
  X.prototype.get_name = function() { return this.name; };

Closure mode:

  

    var Y = function(name) {
    var y = { name: name };

    return { 'get_name': function() { return y.name; } };
  };

Also get_ Name() method, the closure mode is faster.

12. Manage events in pub / sub mode

When an event occurs, if you want to perform multiple operations continuously, you’d better not write it as follows:

  

    function doSomthing{
    doSomethingElse();
    doOneMoreThing();
  }

Instead, use the event triggered form:

  

    function doSomething{
    $.trigger("DO_SOMETHING_DONE");
  }
  $(document).on("DO_SOMETHING_DONE", function(){
    doSomethingElse(); }
  );

You can also consider usingDeferred object

  

    function doSomething(){
    var dfd = new $.Deferred();
    //Do something async, then... 
    //dfd.resolve();
    return dfd.promise();
  }
  function doSomethingElse(){
    $.when(doSomething()).then(//The next thing);
  }

(end)