Jquery performance improvement skills and personal summary

Source: Internet
Author: User

1. cache jquery objects in
In a for loop, do not access the Length attribute of the array every time. We should first cache the object into a variable and then operate it, as shown below:
The Code is as follows:
VaR mylength = myarray. length;
For (VAR I = 0; I <mylength; I ++ ){
// What to do
}

Objects to be cached in the code block:

The Code is as follows:

Items ('items item'detail .css ('color', '#123456 ');
Items ('items item'items .html ('hello ');
Certificate ('background item'0000.css ('background-color', '# ffff ');
// Write better
('Items item'0000.css ('color', '0000123456'0000.html('hello'0000.css ('background-color', '# ffff ');
// Even like this
VaR item = $ ('# item ');
Item.css ('color', '#123456 ');
Item.html ('hello ');
Item.css ('background-color', '# ffff ');

2. Use APPEND outside the loop. The fewer Dom operations, the better.

There is a price to perform Dom operations. If you need to add a large number of elements to the Dom, you should finish it in batches at a time, instead of at a time.
The Code is as follows:
// Don't do this
$. Each (reallylongarray, function (count, item ){
VaR newli = '<li>' + item + '</LI> ';
$ ('# Ballers'). append (newli );
});
// Good practice
VaR frag = Document. createdocumentfragment ();
$. Each (reallylongarray, function (count, item ){
VaR newli = '<li>' + item + '</LI> ';
Frag. appendchild (newli [0]);
});
$ ('# Ballers') [0]. appendchild (frag); do not use the $ ('# id') selector in each (). It will traverse the DOM element multiple times to find the DOM element, and the efficiency is very low. Use document. createdocumentfragment () to reduce the number of Dom structure changes and the number of refreshes on the page

// Or
VaR myhtml = '';
$. Each (myarray, function (I, item ){
HTML + = '<li>' + item + '</LI> ';
});
('{Ballers'{.html (myhtml );

3. Maintain a concise style
The Code is as follows:
// Not ideal
If ($ ventfade. Data ('currently ')! = 'Showing '){
$ Ventfade. Stop ();
}
If ($ venthover. Data ('currently ')! = 'Showing '){
$ Venthover. Stop ();
}
If ($ spans. Data ('currently ')! = 'Showing '){
$ Spans. Stop ();
}
// Better
VaR elems = [$ ventfade, $ venthover, $ spans];
$. Each (elems, function (K, v ){
If (V. Data ('currently ')! = 'Showing '){
V. Stop ();
}
})

4. Optimization Selector
Node Selection and Dom operations, matching an element based on the given ID always uses # ID to find the element
The Code is as follows:
// Very fast
$ ('# Container Div. robotarm ');
// Super fast
$ ('# Iner '). find ('div. robotarm '); use $. FN. the find method is faster, because the first selector does not need to be processed by the selector engine. The fastest selector in jquery is the ID selector. because it is directly from the getelementbyid () method of JavaScript, It is very fast because it is originating in the browser. If you need to select multiple elements, this will inevitably involve Dom traversal and loops. To improve performance, we recommend that you inherit from the latest ID.

The right part of the selector should be as specific as possible, and the left side should not be so specific.
Copy the Code as follows:
// Not optimized
$ ('Div. Data. gonzarez ');
// After Optimization
$ ('. Data TD. gonzarez'); if you can, use tag. class on the right side of the selector, and only tag or. class on the left side.

Avoid excessive specifics
Copy the Code as follows:
$ ('. Data table. Attendees TD. gonzarez ');
// It will be better if you do not write data in the middle
$ ('. Data TD. gonzarez'); the refreshing Dom structure also helps improve the selector performance. The selector engine can run several layers to find that element.

5. Avoid using the untargeted wildcard selector.
Copy the Code as follows:
$ ('. Buttons> *'); // extremely slow
$ ('. Buttons'). Children (); // much faster
$ ('. Gender: Radio'); // no targeted search
$ ('. Gender *: Radio'); // same as above
$ ('. Gender input: Radio'); // This is much better

6. When a large number of elements modify CSS, the style sheet should be used.

If you are using $.fn.css to modify CSS for more than 20 elements, consider adding a style label to improve the speed by 60%.
The Code is as follows:
// More than 20 obviously slow
Certificate ('a.swedberg'0000.css ('color', '# asd123 ');
$ ('<Style type = "text/CSS"> A. swedberg {color: # asd123} </style>'). appendto ('head ');

7. Use $. data instead of $. FN. data will be $. apply data to DOM elements than directly call jquery's selection result $. FN. data is 10 times faster. although, you must first determine the difference between the DOM element and the jquery selection result.
The Code is as follows:
// Common
$ (ELEM). Data (Key, value );
// Ten times faster
$. Data (ELEM, key, value );

// Faster than the second method (non-jquery)

ELEM. Key = value;

8. Don't bother with the blank selection result.

Jquery will not tell you that if the code you want to run is in an empty choice, it will continue to run, as if there is nothing wrong. Performance is affected.
The Code is as follows:
// It was too bad. After executing three methods, I realized that it was empty.
$ ('# Nosuchthing'). slideup ();

// Better
VaR $ myselection = $ ('# nosuchthing ');
If ($ myselection. Length ){
Myselection. slideup ();
}

// Optimal: Add a doonce plugin
Jquery. FN. doonce = function (func ){
This. Length & func. Apply (this );
Return this;
}
$ ('Li. cartitems '). doonce (function (){
// Make it Ajax! \ O/
}); This layer of protection applies to jquery UI widgets, because there are a lot of overhead even if the elements of the operation are empty.

9. Condition judgment
The Code is as follows:
// Old method
If (type = 'foo' | type = 'bar '){...
}

// Good method
If (/^ (FOO | bar) $/. Test (type )){...
}

// Search for objects
If (({
Foo: 1,
Bar: 1
}) [Type]) {...
}

10. Use the latest jquery version

11. Return false to prevent default behavior

The Code is as follows:
$ ('Popup'). Click (function (){
// Launch popup code
Return false;
});

Reference link:

Http://www.jb51.net/article/25530.htm

Http://blog.benhuoer.com/posts/10-tips-for-jquery-performance.html

Http://docs.jquery.com/Main_Page

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.