Issues to be aware of when using jquery to process data

Source: Internet
Author: User

Now the site more and more attention to user experience, the site must be immediate response, the front-end technology is more and more important, before we all use JavaScript, and then appeared a lot of JS framework, call up is also very convenient, but with the page loading more and more data, use jquery time to pay attention to, Some methods seem to be convenient, but the results are poor.

We produced a Site page, showing a total of more than 3,000 data, users choose the appropriate filter criteria, through jquery to control the more than 3,000 data, which shows, which hidden.

After the transformation, the effect is much better than before.

Precautions:

Use of 1.each

Because we want to iterate over these 3,000 elements, each is used, and after debugging we find that each one is really slow, instead of using a for loop

Before the transformation

$ (". Data"). each (function () {

Console.log ($ (this));

});

After the transformation

var data = $ (". Data");

for (i=0;i<data.length;i++) {

Console.log (Data[i]);

}

JavaScript native loop methods for and while are faster than JQuery's. each () method, you should prioritize using native methods.

2. Using the pair selector

In jquery, you can select the same page element with a variety of selectors. The performance of each selector is different, and you should be aware of their performance differences.

(1) Fastest selector: ID selector and element tag Selector

For example, the following statement performs best:

$ (' #id ')

$ (' form ')

$ (' input ')

When these selectors are encountered, jquery internally automatically calls the browser's native methods (such as getElementById ()), so they execute faster.

(2) Slower selector: class selector

The performance of $ ('. ClassName ') depends on the different browsers.

Firefox, Safari, Chrome, opera browsers have native methods Getelementbyclassname (), so the speed is not slow. However, IE5-IE8 does not deploy this method, so this selector will be quite slow in IE.

(3) Slowest selector: Pseudo class selector and property selector

Let's look at examples first. To find out all the hidden elements in a Web page, use the Pseudo-class selector:

$ (': Hidden ')

The example of the property selector is:

$ (' [Attribute=value] ')

These two statements are the slowest because the browser does not have a native method for them. However, the new version of some browsers adds the Queryselector () and Queryselectorall () methods, which can significantly improve the performance of such selectors.

Finally, the performance comparison of different selectors is shown.

Use of 3.show () and Hide ()

When there are not many elements on the page, there is no problem with show and hide, and there are more elements.

We can modify the CSS so that it will be faster

Before the transformation

$ (' #temp1 '). Show ();

$ (' #temp2 '). Hide ();

After the transformation

$ (' #temp1 '). CSS (' Display ', ' block ');

$ (' #temp2 '). CSS (' Display ', ' none ');

4. Jumping out of the loop and terminating the program

There may be multiple loops in the loop, so we have enough conditions to exit the loop or terminate the program, otherwise it will waste a lot of time, but also increase the burden of JS

(1) Break causes the running program to immediately exit the loop that is contained in the inner layer or exit a switch statement.

(2) The Continue statement is similar to the break statement. What's different is that it's not quitting a loop, but starting a new iteration of the loop.

The continue statement can only be used in the loop body of a while statement, Do/while statement, for statement, or For/in statement, and will cause an error in other places!

(3) The return statement is used to specify the value returned by the function. The return statement can only appear in the function body, and anywhere else in the code will cause a syntax error!

When you execute a return statement, the function execution stops even if there are other statements in the body of the function!

Add: The following precautions are not used, but let's put them up.

    1. Use the latest version of jquery

The version of jquery is updated quickly and you should always use the latest version. Because the new version will improve performance, there are many more features.

Here's a look at how different versions of jquery performance differ. Here are the three most common jquery selection statements:

$ ('. Elem ')

$ ('. Elem ', context)

Context.find ('. Elem ')

We tested with 1.4.2, 1.4.4, 1.6 and 23 versions of jquery to see how many times the browser could execute in 1 seconds. The results are as follows:

As you can see, 1.6. Version 2 runs, far more than two old versions. Especially in the first statement, performance is increased several times.

Tests for other statements, such as. attr ("value") and. Val (), are also new versions of jquery that perform better than the old version.

Understanding the relationship between child elements and parent elements

The following six selectors select child elements from a parent element. Do you know which speed 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 in a sentence.

(1) $ ('. Child ', $parent)

This statement means that a DOM object is given, and then a child element is selected from it. jquery automatically turns this statement into $.parent.find (' child '), which results in a certain performance penalty. It is 5%-10% slower than the fastest form.

(2) $parent. Find ('. Child ')

This is the fastest statement: the Find () method invokes the browser's native method (Getelementbyid,getelementbyname,getelementbytagname, and so on), so it is faster.

(3) $parent. Children ('. Child ')

Within jquery, this statement iterates through the nodes using the $.sibling () and JavaScript nextsibling () methods. It is about 50% slower than the fastest form.

(4) $ (' #parent >. Child ')

jquery internally uses the sizzle engine to handle a variety of selectors. The sizzle engine is selected from right to left, so this statement is selected first. Child, and then filters out the parent element #parent, which causes it to be about 70% slower than the fastest form.

(5) $ (' #parent. Child ')

This statement is the same as the previous one. However, the previous bar selects only the immediate child element, which can be used to select a multilevel sub-element, so it is slower and probably 77% slower than the fastest form.

(6) $ ('. Child ', $ (' #parent '))

Within jquery, this statement is converted to $ (' #parent '). Find ('. Child '), which is 23% slower than the fastest form.

Therefore, the best choice is $parent.find ('. Child '). Furthermore, because $parent often has been generated in the previous operations, jquery caches it, so the execution speed is further accelerated.

For specific examples and comparison results, see here.

Don't use jquery too much

jquery is no faster and can be compared to native JavaScript methods. So there are native methods that can be used in situations where try to avoid using jquery.

Consider the following example, binding a function that handles a click event for a element:

$ (' a '). Click (function () {

Alert ($ (this). attr (' id '));

});

This code means that after clicking the a element, the id attribute of the element pops up. In order to get this property, jquery must be called twice in succession, the first is $ (this), and the second is attr (' id ').

In fact, such treatment is completely unnecessary. The more correct way to do this is to use the JavaScript native method directly, calling This.id:

$ (' a '). Click (function () {

alert (this.id);

});

According to the test, this.id speed is more than 20 times faster than $ (this). attr (' id ').

Do cache

Selecting a page element is a costly step. Therefore, you should use selectors as few times as possible, and cache the selected results as much as you want, so that you can reuse them later.

For example, the following is a bad way to do this:

JQuery (' #top '). Find (' P.classa ');

JQuery (' #top '). Find (' P.CLASSB ');

A better notation is:

var cached = JQuery (' #top ');

Cached.find (' P.classa ');

Cached.find (' P.CLASSB ');

According to the test, the cache is 2-3 times faster than no cache.

Use chained notation

One of the major features of jquery is that it allows you to use chained notation.

$ (' div '). Find (' H3 '). EQ (2). html (' Hello ');

When using chained notation, jquery automatically caches the results of each step, so it is faster than non-chained notation. Depending on the test, the chained notation is about 25% faster than the non-chained notation (without using the cache).

    1. Delegate handling of events (event delegation)

The JavaScript event model, in "bubbling" mode, in other words, the child element's events are "bubbling up" to become the parent element's event.

With this, you can greatly simplify the binding of events. For example, there is a table (table element) with 100 squares (TD elements), which now requires a click event to be bound on each grid (click), do I need to execute the following command 100 times?

$ ("TD"). BIND ("click", Function () {

$ (this). Toggleclass ("click");

});

The answer is no, we just have to bind this event to the table element, because after the click event of the TD element, the event will "bubble" to the parent element table and be heard.

Therefore, this event only needs to be bound to the parent element 1 times, without having to bind the child element 100 times, thereby greatly improving performance. This is called the "delegate Processing" of the event, which is the child element "delegate" The parent element handles the event.

There are two kinds of specific wording. The first is the use of the. Delegate () Method:

$ ("table"). Delegate ("TD", "click", Function () {

$ (this). Toggleclass ("click");

});

The second is the use of the. Live () Method:

$ ("table"). each (function () {

$ ("TD", this). Live ("Click", Function () {

$ (this). Toggleclass ("click");

});

});

These two types of writing are basically equivalent. The only difference is that. Delegate () is triggered when an event bubbles to the specified parent element, and. Live () is triggered when the event bubbles to the root element of the document, so. Delegate () is slightly faster than. Live (). In addition, there is a benefit to the two methods compared to the traditional. Bind () method, which is also valid for dynamically inserted elements. Bind () is valid only for DOM elements that already exist and is not valid for dynamically inserted elements.

According to the test, the delegate processing is dozens of times times faster than the delegate processing. In the case of delegate processing,. Delegate () is about 26% faster than. Live ().

    1. Change the DOM structure less

(1) It is expensive to change the DOM structure, so do not use the. Append (),. InsertBefore (), and. Insetafter () methods frequently.

If you want to insert multiple elements, merge them first, and then insert them once. According to the test, the merge insert is nearly 10 times times faster than not merging inserts.

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

(3) If you want to store data on DOM elements, do not write the following:

var elem = $ (' #elem ');

Elem.data (Key,value);

and to write:

var elem = $ (' #elem ');

$.data (Elem,key,value);

According to the test, the latter is nearly 10 times times faster than the previous one. Because the Elem.data () method is defined above the prototype object of the jquery function, and the $.data () method is defined above the jquery function, the call is not invoked from a complex jquery object, so it is much faster. (see 10th below.) )

    1. Create as few jquery objects as possible

Whenever you use a selector (such as $ (' #id ')), a jquery object is generated. The jquery object is a huge object with many properties and methods that can take up a lot of resources. Therefore, create as few jquery objects as possible.

For example, many jquery methods are available in two versions, one for jquery objects, and the other for jquery functions. The following two examples are the text that takes out an element, and all that is used is the literal () method. You can use both versions of the jquery object:

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 the jquery function does not operate through jquery objects, the relative overhead is relatively small and faster.

9. Multiple if else loops change to switch

10. There are a lot of global variables, easy to mix, you can make an object, each function is written as a separate object, logical code is the method of the object

11. The function is similar to the JS code alone into a method, you can use the Factory mode of the kind, transfer parameters call their own pipeline operations

12. Get the parent node's method before writing a little silly, $ (' div '). Parent (). Parent () This multilayer lookup, changed to $ (' div '). Parents ()

Issues to be aware of when using jquery to process data

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.