Explore the mysteries of efficient jquery

Source: Internet
Author: User

Good code can lead to speed improvements. Fast rendering and responsiveness means a better user experience.
First, keep in mind that jquery is JavaScript. This means that we should take the same coding conventions, style guides and best practices.

First of all, if you're a novice JavaScript, I suggest you read the 24 best practices for JavaScript beginners , a high-quality JavaScript tutorial that you'd better read before contacting jquery.

When you are ready to use jquery, I strongly recommend that you follow these guidelines:

Cache variables
DOM traversal is expensive, so try to cache the elements that will be reused.

    1. Bad
    2. H = $ (' #element '). Height ();
    3. $ (' #element '). CSS (' height ', h-20);
    4. Suggestions
    5. $element = $ (' #element ');
    6. h = $element. Height ();
    7. $element. css (' height ', h-20);
Copy Code


Avoid global variables

jquery, like JavaScript, is generally preferable to ensure that your variables are within the scope of the function.

    1. Bad
    2. $element = $ (' #element ');
    3. h = $element. Height ();
    4. $element. css (' height ', h-20);
    5. Suggestions
    6. var $element = $ (' #element ');
    7. var h = $element. Height ();
    8. $element. css (' height ', h-20);
Copy Code


Using the Hungarian nomenclature

Prefix the variable with $ to make it easy to identify the jquery object.

    1. Bad
    2. var first = $ (' #first ');
    3. var second = $ (' #second ');
    4. var value = $first. val ();
    5. Recommendation-add $ prefix to jquery objects
    6. var $first = $ (' #first ');
    7. var $second = $ (' #second '),
    8. var value = $first. val ();
Copy Code


Using the var chain (single var mode)

To combine multiple VAR statements into one statement, I recommend that you put unassigned variables behind.

    1. Var
    2. $first = $ (' #first '),
    3. $second = $ (' #second '),
    4. Value = $first. val (),
    5. K = 3,
    6. cookiestring = ' Somecookiesplease ',
    7. I
    8. J
    9. MyArray = {};
Copy Code


Please use ' on '

In the new version of jquery, Shorter on ("click") is used to replace functions like Click (). In the previous version, on () is bind (). The preferred method of on () attaching event handlers since the jquery 1.7 release. However, for consistency reasons, you can simply use the on () method.

    1. Bad
    2. $first. Click (function () {
    3. $first. CSS (' border ', ' 1px solid red ');
    4. $first. CSS (' Color ', ' blue ');
    5. });
    6. $first. Hover (function () {
    7. $first. CSS (' border ', ' 1px solid red ');
    8. })
    9. Suggestions
    10. $first. On (' click ', function () {
    11. $first. CSS (' border ', ' 1px solid red ');
    12. $first. CSS (' Color ', ' blue ');
    13. })
    14. $first. On (' hover ', function () {
    15. $first. CSS (' border ', ' 1px solid red ');
    16. })
Copy Code


Thin JavaScript

In general, it is best to combine functions as much as possible.

    1. Bad
    2. $first. Click (function () {
    3. $first. CSS (' border ', ' 1px solid red ');
    4. $first. CSS (' Color ', ' blue ');
    5. });
    6. Suggestions
    7. $first. On (' click ', function () {
    8. $first. CSS ({
    9. ' Border ': ' 1px solid red ',
    10. ' Color ': ' Blue '
    11. });
    12. });
Copy Code


Chained operation

The chained operation of the jquery implementation method is very easy. Use this point below.

    1. Bad
    2. $second. HTML (value);
    3. $second. On (' click ', function () {
    4. Alert (' Hello everybody ');
    5. });
    6. $second. FadeIn (' slow ');
    7. $second. Animate ({height: ' 120px '},500);
    8. Suggestions
    9. $second. HTML (value);
    10. $second. On (' click ', function () {
    11. Alert (' Hello everybody ');
    12. }). FadeIn (' slow '). Animate ({height: ' 120px '},500);
Copy Code


Maintain the readability of your code

Along with the streamlining of code and the use of chaining, the code can be difficult to read. Adding a shrink and line break can be a good result.

    1. Bad
    2. $second. HTML (value);
    3. $second. On (' click ', function () {
    4. Alert (' Hello everybody ');
    5. }). FadeIn (' slow '). Animate ({height: ' 120px '},500);
    6. Suggestions
    7. $second. HTML (value);
    8. $second
    9. . On (' click ', function () {alert (' Hello Everybody ');})
    10. . FadeIn (' slow ')
    11. . Animate ({height: ' 120px '},500);
Copy Code


Select short-Circuit evaluation

A short-circuit evaluation is an expression that evaluates from left to right, with && (logical AND) or | | (logical OR) operators.

    1. Bad
    2. function Initvar ($myVar) {
    3. if (! $myVar) {
    4. $myVar = $ (' #selector ');
    5. }
    6. }
    7. Suggestions
    8. function Initvar ($myVar) {
    9. $myVar = $myVar | | $ (' #selector ');
    10. }
Copy Code


Choose a shortcut

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

    1. Bad
    2. if (Collection.length > 0) {..}
    3. Suggestions
    4. if (collection.length) {..}
Copy Code


Separation of elements in heavy operations

If you are going to do a lot of work on DOM elements (setting multiple properties or CSS styles consecutively), it is recommended that you first detach the elements and then add them.

    1. Bad
    2. Var
    3. $container = $ ("#container"),
    4. $containerLi = $ ("#container Li"),
    5. $element = null;
    6. $element = $containerLi. First ();
    7. //... Many complex operations
    8. Better
    9. Var
    10. $container = $ ("#container"),
    11. $containerLi = $container. Find ("Li"),
    12. $element = null;
    13. $element = $containerLi. First (). Detach ();
    14. //... Many complex operations
    15. $container. Append ($element);
Copy Code


Memorizing skills

You may have a lack of experience with the methods in jquery, be sure to review the documentation, and there may be a better or faster way to use it.

    1. Bad
    2. $ (' #id '). Data (Key,value);
    3. Recommended (efficient)
    4. $.data (' #id ', key,value);
Copy Code


Using the parent element of a subquery cache

As mentioned earlier, Dom traversal is an expensive operation. A typical practice is to cache the parent element and reuse those cached elements when the child element is selected.

    1. Bad
    2. Var
    3. $container = $ (' #container '),
    4. $containerLi = $ (' #container Li '),
    5. $containerLiSpan = $ (' #container Li span ');
    6. Recommended (efficient)
    7. Var
    8. $container = $ (' #container '),
    9. $containerLi = $container. Find (' Li '),
    10. $containerLiSpan = $containerLi. Find (' span ');
Copy Code


Avoid Universal selectors

It is very bad to put a generic selector in a descendant selector.

    1. Bad
    2. $ ('. Container > * ');
    3. Suggestions
    4. $ ('. Container '). Children ();
Copy Code


Avoid implicit universal selectors

Universal selectors are sometimes implicit and not easily discoverable.

    1. Bad
    2. $ ('. Someclass:radio ');
    3. Suggestions
    4. $ ('. SomeClass input:radio ');
Copy Code


Refine selectors

For example, the ID selector should be unique, so there is no need to add additional selectors.

    1. Bad
    2. $ (' Div#myid ');
    3. $ (' Div#footer a.mylink ');
    4. Suggestions
    5. $ (' #myid ');
    6. $ (' #footer. MyLink ');
Copy Code


Avoid multiple ID selectors
in this emphasis, the ID selector should be unique, no additional selectors need to be added, and more than one descendant ID selector is required.

    1. Bad
    2. $ (' #outer #inner ');
    3. Suggestions
    4. $ (' #inner ');
Copy Code


Stick to the latest version

The new version is usually better: more lightweight and more efficient. Obviously, you need to consider the compatibility of the code you want to support. For example, the 2.0 version does not support IE 6/7/8. It is important to discard deprecated methods that focus on each new version and avoid using them as much as possible.

    1. Bad
    2. $ (' #outer #inner ');
    3. Suggestions
    4. $ (' #inner ');
Copy Code


Leveraging CDN

Google's CND ensures that the most recent cache is selected from the user and responds quickly. (Use Google CND, please search the address, where the address can not be used, recommended by the jquery website CDN).

Combine jquery and JavaScript native code if necessary
As mentioned above, jquery is JavaScript, which means that what you can do with jquery can also be done using native code. Native code (or vanilla) may be less readable and maintainable than jquery, and the code is longer. But it also means more efficient (often closer to lower-level code readability and higher performance, for example: compilation, which of course requires more powerful talent). Keep in mind that no framework can be smaller, lighter, and more efficient than native code (note: The test link is invalid and the test code can be searched online). Given the performance differences between vanilla and jquery, it is highly recommended to absorb the essence of both, using (possibly) and jquery equivalent native code .

Explore the mysteries of efficient jquery

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.