JQuery performance optimization manual _ jquery

Source: Internet
Author: User
Nowadays, more and more jquery applications are available. Some people ignore performance problems when enjoying coding, such as me. although jquery has excellent performance in many js class libraries, it is not developed using native javascript, and performance issues still need to be paid attention. found on twitter This article is a simple excerpt:

Always inherit from ID Selector
Use tags before class
Cache jquery objects
Powerful chain operations
Use subquery
Restrict direct DOM operations
Bubble
Clear invalid Query
Postponed to $ (window). load
Compressing js
Comprehensive Understanding of the jquery Library
1. always inherit from the ID Selector
The fastest selector in jquery is the ID selector because it comes directly from the getElementById () method of Javascript.

The Code is as follows:






Selecting buttons like this is inefficient:

The Code is as follows:


Var traffic_button = $ ('# content. click ');


Using ID to select buttons is more efficient:

The Code is as follows:


Var traffic_button = $ ('# traffic_button ');


Select multiple elements

Multi-element selection is actually about DOM traversal and loops, which are slow. To improve performance, it is best to inherit from the nearest ID.

The Code is as follows:


Var traffic_lights = $ ('# traffic_light input ');


2. Use tags before the class

The second fast selector is the tag selector ($ ('head'). Likewise, because it comes from the native getElementsByTagName () method.

The Code is as follows:






Always use a tag name to restrict (modify) class (and do not forget the nearest ID ):

The Code is as follows:


Var active_light = $ ('# traffic_light input. on ');


Note: In jquery, the Class is the slowest selector. in IE browser, it will traverse all DOM nodes regardless of where it is used.

Do not use the tag name to modify the ID. The following example will traverse all p elements to find which node with the id as 'content:

The Code is as follows:


Var content = $ ('P # content ');


Modifying the ID with ID is also a superfluous addition:

The Code is as follows:


Var traffic_light = $ ('# content # traffic_light ');


3. cache jquery objects

You need to develop the habit of caching jquery objects into variables.

Never do this:

The Code is as follows:


$ ('# Traffic_light input. on). bind ('click', function (){...});
$ ('# Traffic_light input.on).css ('border', '3px dashed yellow ');
$ ('# Traffic_light input.on).css ('background-color', 'Orange ');
$ ('# Traffic_light input. on). fadeIn ('low ');


It is best to cache the object into a variable before the operation:

The Code is as follows:


Var $ active_light = $ ('# traffic_light input. on ');
$ Active_light.bind ('click', function (){...});
Using active_light.css ('border', '3px dashed yellow ');
Using active_light.css ('background-color', 'Orange ');
$ Active_light.fadeIn ('low ');


To remember that our local variables are jquery encapsulation, we usually use a $ prefix as the variable. Remember, never let the same selector appear multiple times in your code.

Cache jquery results, standby

If you plan to use jquery result objects in other parts of the program, or your function will be executed multiple times, they will be cached in a global variable.

Define a global container to store jquery results. We can reference them in other functions:

The Code is as follows:


// Define an object globally (for example, window object)
Window. $ my =
{
// Initialize all queries that may be used more than once
Head: $ ('head '),
Traffic_light: $ ('# traffic_light '),
Traffic_button: $ ('# traffic_button ')
};

Function do_something ()
{
// Now you can reference the stored results and operate on them
Var script = document. createElement ('script ');
$ My. head. append (script );

// When you perform an internal operation in the function, you can continue to save the query to the global object.
$ My. cool_results = $ ('# some_ul li ');
$ My. other_results = $ ('# some_table td ');

// Use the global function as a common jquery object.
Export my.other_results.css ('border-color', 'red ');
Using my.traffic_light.css ('border-color', 'green ');
}


4. Powerful chain operations

The preceding example can also be written as follows:

The Code is as follows:


Var $ active_light = $ ('# traffic_light input. on'); $ active_light.bind ('click', function (){...})
. Css ('border', '3px dashed yellow ')
. Css ('background-color', 'Orange ')
. FadeIn ('slow ');


In this way, we can write less code to make our js more lightweight.

5. Use subquery

JQuery allows us to use an additional selector operation on a encapsulated object, because we have saved a parent-level object in the variable, which greatly improves the operation on its child elements:

The Code is as follows:






For example, we can use the subquery method to capture bright or non-bright lights and cache them for subsequent operations.

The Code is as follows:


Var $ traffic_light = $ ('# traffic_light '),
$ Active_light = $ traffic_light.find ('input. on '),
$ Inactive_lights = $ traffic_light.find ('input. off ');


Tip: You can declare multiple local variables at a time using commas (,) to save the number of bytes.

6. restrict direct DOM operations

The basic idea here is to create what you really want in the memory and then update the DOM. This is not a jQuery best practice, but it must be used for effective JavaScript operations. Direct DOM operations are slow.

For example, if you want to dynamically create a group of list elements, do not do this:

The Code is as follows:


Var top_100_list = [...], // assume there are 100 unique strings.
$ Mylist = $ ('# mylist'); // select

    Element for (var I = 0, l = top_100_list.length; I {
    $ Mylist. append ('
  • '+ Top_100_list [I] +'
  • ');
    }


    We should create all the element strings before inserting them into the dom:

    The Code is as follows:


    Var top_100_list = [...],
    $ Mylist = $ ('# mylist '),
    Top_100_li = ""; // This variable will be used to store our list element for (var I = 0, l = top_100_list.length; I {
    Top_100_li + ='

  • '+ Top_100_list [I] +'
  • ';
    }
    Using mylist.html (top_100_li );


    It is faster to wrap multiple elements into a single parent node before insertion:

    The Code is as follows:


    Var top_100_list = [...],
    $ Mylist = $ ('# mylist '),
    Top_100_ul ='

      '; For (var I = 0, l = top_100_list.length; I {
      Top_100_ul + ='
    • '+ Top_100_list [I] +'
    • ';
      }
      Top_100_ul + ='
    '; // Close the unordered list
    $ Mylist. replaceWith (top_100_ul );


    If you are still worried about performance issues after the above steps:
  • Try jquery's clone () method to create a copy of the node tree. It allows dom operations in an "offline" manner, after the operation is complete, you can put it back in the node tree.
  • Use DOM DocumentFragments. As the author of jQuery says, its performance is much better than direct dom operations.
    7. Bubble

    Unless in special circumstances, every js event (such as click, mouseover, etc .) will bubble to the parent node. this is useful when we need to call the same function for multiple elements.

    Instead of this inefficient multi-element event listening method, you only need to bind them to their parent nodes once and can calculate which node triggers the event.

    For example, we need to bind a form with many input boxes to add a class when the input box is selected.

    Binding events like this is inefficient:

    The Code is as follows:


    $ ('# Entryform input). bind ('core', function (){
    $ (This). addClass ('selected ');
    }). Bind ('blur', function (){
    $ (This). removeClass ('selected ');
    });


    We need to obtain the focus and the loss of the Focus event in the parent listener:

    The Code is as follows:


    $ ('# Entryform'). bind ('core', function (e ){
    Var cell = nodes (e.tar get); // e.tar get grabs the node that triggered the event.
    Cell. addClass ('selected ');
    }). Bind ('blur', function (e ){
    Var cell = require (e.tar get );
    Cell. removeClass ('selected ');
    });


    The parent element plays the role of a dispatcher. It can bind events based on the target element. If you find that many elements are bound to the same event listener, you must have done something wrong.
    8. Clear invalid queries
    Although jquery can elegantly deal with the absence of matching elements, it still takes time to find them. if you only have one global js on the entire site, it is very likely that you will put all jquery functions into $ (document) ready (function () {// all your proud code.
    Only the functions used in the page are run. Most of the effective methods are to use the in-row initialization function, so that your template can accurately control when and where to execute js.
    For example, in your "article" Page Template, you may reference the following code at the end of the body:

    The Code is as follows:


Related Article

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.