jquery feature: A Guide to performance optimization

Source: Internet
Author: User
Tags object bind event listener functions variables tag name variable jquery library
Although jquery in many JS Class library performance is outstanding, but not in the native JavaScript development, performance problems still need to be paid attention to.

Now jquery applications are more and more, some students enjoy a brisk dripping coding when the performance problem is ignored, such as me. Although jquery in many JS Class library performance is outstanding, but not in the native JavaScript development, performance problems still need to be paid attention to.

    1. Always inherit from ID selector
    2. Use the tag before class
    3. Caching a JQuery object
    4. Mastering the powerful chain operation
    5. Using subqueries
    6. Restricting direct DOM operations
    7. Bubble
    8. Eliminate invalid queries
    9. Defer to $ (window). Load
    10. Compress JS
    11. Full control of the jquery library

1. Always inherit from ID selector

The fastest selector in jquery is the ID selector. Because it comes directly from the JavaScript getElementById () method



traffic light



  • red

  • yellow





Selecting buttons like this is inefficient:

var Traffic_button = $ (' #content. Button ');

Selecting a button directly with an ID is more efficient:

var Traffic_button = $ (' #traffic_button ');

Select multiple elements

The reference to multiple element selection is actually talking about DOM traversal and looping, which are slow things. To improve performance, it is best to inherit from the nearest ID.

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

2. Use tag before class

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



traffic light



  • red

  • yellow





;

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

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

Note: class is the slowest selector in jquery. In IE, it traverses all DOM nodes regardless of where it is used.

Do not use tag name to decorate IDs. The following example iterates through all the DIV elements to find which node ID is ' content ':

var content = $ (' div#content ');

Using an ID to decorate the ID is also superfluous:

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

3. Cache the jquery objects

Get into the habit of caching a jquery object into a variable.

Never do this:

$ (' #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 (' slow ');

It's a good idea to cache objects into a variable before you manipulate it:

var $active _light = $ (' #traffic_light input.on ');
$active _light.bind (' click ', function () {...});
$active _light.css (' border ', ' 3px dashed yellow ');
$active _light.css (' Background-color ', ' orange ');
$active _light.fadein (' slow ');

to keep in mind that our local variables are encapsulated in jquery, we usually prefix it with a $. Remember, never let the same selector appear more than once in your code.

Cache jquery results, standby

If you intend to use the jquery results object in other parts of your program, or if your function executes multiple times, then cache them in a global variable.

By defining a global container to store the jquery results, we can reference them in other functions:

Defines an object (for example: Window object) in the global scope
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 refer to the stored results and manipulate them
var script = document.createelement (' script ');
$my. Head.append (script);

When you operate inside a function, you can continue to store the query in the global object.
$my. Cool_results = $ (' #some_ul Li ');
$my. Other_results = $ (' #some_table TD ');

Use global functions as a common jquery object.
$my. Other_results.css (' Border-color ', ' red ');
$my. Traffic_light.css (' Border-color ', ' green ');
}

4. Master the powerful chain-type operation

The example above can also be written like this:

var $active _light = $ (' #traffic_light input.on '); $active _light.bind (' click ', function () {...})
. css (' border ', ' 3px dashed yellow ')
. css (' background-color ', ' orange ')
. FadeIn (' slow ');

This can be written less code, so that our JS lighter volume.

5. Use a subquery

JQuery allows us to use additional selector actions on a wrapped object. Because we have saved a parent object in a variable, this greatly increases the operation of its child elements:



traffic light



  • red

  • yellow





For example, we can use the subquery method to grab the light or not light, and cache it for subsequent operation.

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 one at a time by using a comma-delimited method-Save the number of bytes


6. Restrictions on direct DOM operations

The basic idea here is to create what you really want in memory, and then update the DOM. This is not a jquery best practice, but it must be a valid JavaScript operation. The direct DOM operation is slow.

For example, if you want to create a set of list elements dynamically, don't do this:

var top_100_list = [...],//Suppose this is a 100 unique string
$mylist = $ (' #mylist '); JQuery selection to
    elements

    For (var i=0, l=top_100_list.length; i{
    $mylist. Append ('

  • ' + top_100_list[i] + '
  • ');
    }

    We should create the entire set of element strings before inserting them into the DOM:

    var top_100_list = [...],
    $mylist = $ (' #mylist '),
    Top_100_li = ""; This variable will be used to store our list elements.

    For (var i=0, l=top_100_list.length; i{
    Top_100_li + = '

  • ' + top_100_list[i] + '
  • ';
    }
    $mylist. HTML (TOP_100_LI);

    We will be quicker to wrap multiple elements into a single parent node before inserting:

    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 + = '
    '; Turn off unordered lists
    $mylist. ReplaceWith (Top_100_ul);

    If you've done a few of these or are worried about performance problems, then:

      • Try the jquery Clone () method, which creates a copy of the node tree that allows you to do DOM operations in an "offline" manner, and then put it back in the node tree when you're done.
      • Use DOM documentfragments. As the jquery author puts it, its performance is significantly better than direct DOM operations.

    7. Bubbling

    Unless in exceptional circumstances, otherwise each JS event (for example: click, mouseover, etc.) Will bubble to the parent node. This can be useful when we need to call the same function for multiple elements.

    Instead of this inefficient, multiple-element event listener, you only have to bind to their parent node once, and you can calculate which node triggers the event.

    For example, we want to bind a form with many input boxes to do this: Add a class to it when the input box is selected

    Binding events like this is inefficient:

    $ (' #entryform input '). Bind (' Focus ', function () {
    $ (this). AddClass (' selected ');
    }. Bind (' blur ', function () {
    $ (this). Removeclass (' selected ');
    });

    We need to listen to the events in the parent to get focus and lose focus:

    $ (' #entryform '). Bind (' Focus ', function (e) {
    var cell = $ (e.target); E.target grabs the node that triggered the event.
    Cell.addclass (' selected ');
    }. Bind (' blur ', function (e) {
    var cell = $ (e.target);
    Cell.removeclass (' selected ');
    });

    The parent element plays the role of a dispatcher, which can bind events based on the target element. If you find that you have a lot of elements bound to the same event listener, then you must have done something wrong.

    8. Eliminate invalid Query

    Although jquery can gracefully handle a situation where there are no matching elements, it still takes time to find it. If you have only one global JS in the entire station, it is very likely that all of the jquery functions will be stuffed into $ (document) Ready (function () {//All your Proud code}).

    Only functions that are used in the page are run. The most effective approach is to use inline initialization functions so that your template can control exactly when and where to execute JS.

    For example, your "article" page template, you might refer to the following code at the end of the body:

    Your Global JS library might be like this:

    var mylib =
    {
    Article_page:
    {
    Init:function ()
    {
    Article's unique jquery function.
    }
    },
    Traffic_light:
    {
    Init:function ()
    {
    Traffic Light's unique jquery function.
    }
    }
    }

    9. Defer to $ (window). Load

    jquery has a tempting thing for developers to hang anything up to $ (document). Ready under a fake event. In most cases, you will find this.

    Although the $ (document). Rady is really useful, it can be performed when the page is rendered and the other elements are not finished downloading. If you find that your page has been in the loading state, it is likely to be $ (document). The Ready function causes.

    You can reduce the CPU usage when the page is loaded by binding the jquery function to the $ (window). Load event method. It will be executed after all HTML (including ) is downloaded.</p></p>$ (window). Load (function () { <br>The jquery function that is initialized when the page is fully loaded. <br>}); <p><p>Redundant features such as drag-and-drop, visual effects and animations, preload hidden images, and so on. are all suitable for this kind of technology occasion.</p></p> <p><p>10. Compression JS</p></p> <p><p>Recommend a JS online compression address: http://dean.edwards.name/packer/</p></p> <br> <br>

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.