Jquery optimization rules

Source: Internet
Author: User
ArticleDirectory
    • Selecting Single Elements
    • Selecting Multiple Elements
    • Bonus tip-storing jquery results for later

Once upon a time, all we needed to worry about was memory cing bytes and
Requests and playing around und with load order to make things faster.
Nowadays, we are increasingly impacting one more major component in
Performance-CPU utilization. Using jquery and other
Frameworks that make selecting nodes and Dom manipulation easy can have
Adverse affects if you're not careful and follow some simple practices
For processing the work the browser has to do.

    1. Always descend from an # ID
    2. Use tags before classes
    3. Cache jquery objects
    4. Harness the power of chaining
    5. Use sub-queries
    6. Limit direct Dom manipulation
    7. Leverage event delegation (a.k. A. bubbling)
    8. Eliminate query waste
    9. Defer to $ (window). Load
    10. Compress Your JS
    11. Learn the library

1. Always descend from an # ID

The fastest selector in jquery is the ID selector ($ ('# Someid ')). This is because it maps directly to a native JavaScript method,Getelementbyid ().

Selecting Single Elements

<Div id = "content"> <form method = "Post" Action = "/"> <H2> traffic light </H2> <ul id = "traffic_light"> <li> <input type = "radio" class = "on" name = "light" value = "red"/> Red </LI> <li> <input type = "radio" class = "off" name = "light" value = "yellow"/> yellow </LI> <li> <input type = "radio" class = "off" name =" light "value =" green "/> green </LI> </ul> <input class =" button "id =" traffic_button "type =" Submit "value =" go" /> </form> </div>

Selecting the button like this is slower:

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

Instead, select the button directly:

 
VaR traffic_button = $ ('# traffic_button ');

Selecting Multiple Elements

Once we start talking about selecting multiple elements, we are
Really talking about Dom traversal and looping, something that is slow.
To minimize the performance hit,Always descend from the closest parent ID:

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

2. Use tags before classes

The second fastest selector in jquery is the tag selector ($ ('Head ')). Again, this is because it maps to a native JavaScript method,Getelementsbytagname ()

.

<Div id = "content"> <form method = "Post" Action = "/"> <H2> traffic light </H2> <ul id = "traffic_light"> <li> <input type = "radio" class = "on" name = "light" value = "red"/> Red </LI> <li> <input type = "radio" class = "off" name = "light" value = "yellow"/> yellow </LI> <li> <input type = "radio" class = "off" name =" light "value =" green "/> green </LI> </ul> <input class =" button "id =" traffic_button "type =" Submit "value =" go" /> </form> </div>

Always prefix a class with a tag name (and remember to descend from an ID ):

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

Note: The class selector is among the slowest selectors in
Jquery; In ie It loops through the entire DOM. Avoid using it whenever
Possible.
Never prefix an ID with a tag name. For example, this is slow because it will loop through all<Div>Elements looking for the 'content' ID:

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

Along the same lines, it is redundant to descend from multiple IDs:

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

3. cache jquery objects

Get in the habit of saving your jquery objects to a variable (much
Like our examples above). For example, never (eeeehhhhver) 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 ');

Instead, first save the object to a local variable, and continue your operations:

 
VaR $ active_light = $ ('# traffic_light input. on '); $ active_light.bind ('click', function()...20.20.20.20.active_light.css ('border', '3px dashed yellow'{{active_light.css ('background-color', 'Orange '); $ active_light.fadein ('low ');

Tip: since we want to remember that our local variable is a jquery wrapped set, we are using $ as a prefix.Remember,Never repeat a jquery selection operationMore than once in your application.

Bonus tip-storing jquery results for later

If you intend to use the jquery result object (s) in another part
Your program, or shocould your function execute more than once, cache it
In an object with a global scope. by defining a global container with jquery results, we can reference them from within other functions:

// Define an object in the global scope (I. e. the window object) window. $ my = {// Initialize all the queries you want to use more than oncehead: $ ('head'), traffic_light: $ ('# traffic_light'), traffic_button: $ ('# traffic_button')}; function do_something () {// now you can reference the stored results and manipulate themvar script = document. createelement ('script'); $ my. head. append (SCRIPT); // when working inside functions, continue to save jquery results // to your global container. $ my. cool_results = $ ('# some_ul li'); $ my. other_results = $ ('# some_table TD'); // use the global functions as you wocould a normal jquery resultextension my.other_results.css ('border-color', histogram ('border-color ', 'green ');}

4. harness the power of chaining

The previous example can also be accomplished like this:

VaR $ active_light = $ ('# traffic_light input. on '); $ active_light.bind ('click', function()...hangzhou.css ('border', '3px dashed yellow'hangzhou.css ('background-color', 'Orange '). fadein ('slow ');

This allows us to write less code, making our JavaScript more lightweight.

5. Use sub-queries

Jquery allows us to run additional selector operations on a wrapped
Set. This reduces performance overhead on Subsequent selections since we
Already grabbed and stored the parent object in a local variable.

<Div id = "content"> <form method = "Post" Action = "/"> <H2> traffic light </H2> <ul id = "traffic_light"> <li> <input type = "radio" class = "on" name = "light" value = "red"/> Red </LI> <li> <input type = "radio" class = "off" name = "light" value = "yellow"/> yellow </LI> <li> <input type = "radio" class = "off" name =" light "value =" green "/> green </LI> </ul> <input class =" button "id =" traffic_button "type =" Submit "value =" go" /> </form> </div>

For example, we can leverage sub-queries to grab the active and inactive lights and cache them for later manipulation.

 
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 by separating them with commas-save those bytes!

6. limit direct Dom manipulation

The basic idea here is to create exactly what you need in memory, andThenUpdate the Dom. this is not a jquery best practice, but a must for efficient JavaScript. direct Dom manipulation is slow. for example, if you need to dynamically create a list of elements, do not do this:

 
VaR top_100_list = [...], // assume this has 100 unique strings $ mylist = $ ('# mylist'); // jquery selects our <ul> elementfor (VAR I = 0, L = top_100_list.length; I <L; I ++) {$ mylist. append ('<li>' + top_100_list [I] + '</LI> ');}

Instead, we want to create the entire set of elements in a string before inserting into the DOM:

VaR top_100_list = [...], // assume this has 100 unique strings $ mylist = $ ('# mylist'), // jquery selects our <ul> elementtop_100_li = ""; // This will store our list itemsfor (VAR I = 0, L = top_100_list.length; I <L; I ++) {top_100_li + = '<li>' + top_100_list [I] + '</LI> '{$$mylist.html (top_100_li );

Even faster, we shocouldAlways wrap extends ElementsIn a single parent node before insertion:

 
VaR top_100_list = [...], // assume this has 100 unique strings $ mylist = $ ('# mylist '), // jquery selects our <ul> elementtop_100_ul = '<ul id = "# mylist">'; // This will store our entire unordered listfor (VAR I = 0, L = top_100_list.length; I <L; I ++) {top_100_ul + = '<li>' + top_100_list [I] + '</LI> ';} top_100_ul + = '</ul>'; // close our unordered list $ mylist. replacewith (top_100_ul );

If you do the above and are still concerned about performance:

    • Give jquery'sClone ()Method A try. This creates a copy
      Of the node tree, which you can manipulate "off-line" and then insert
      Back in when you are ready.
    • Use Dom documentfragments. as the creator of jquery points out,
      They perform much better than direct Dom manipulation. The idea wocould
      Be to create what you need (similar to what we did above with a string ),
      And use the jquery insert or replace methods.
7. Leverage event delegation (a.k. A. bubbling)

Unless told otherwise,
Every event (e.g. Click, Mouseover, etc.) In JavaScript "bubbles" up
The DOM tree to parent elements. This is incredibly useful when we want
Elements (nodes) to call the same function. Instead of binding
Event listener function to invoke nodes-very inefficient-you canBind it once
To their parent, and have it figure out which node triggered the event.
For example, say we are developing a large form with your inputs, and
Want to toggle a class name when selected. A binding like this is
Inefficient:

 
$ ('# Mylist Li). BIND ('click', function () {$ (this). addclass ('clicked'); // do stuff });

Instead, we shoshould listen for the click event at the parent level:

$ ('# Mylist ). BIND ('click', function (e) {var target = e.tar get, // e.tar get grabs the node that triggered the event. $ target = $ (target); // wraps the node in a jquery objectif (target. nodename = 'lil') {$ target. addclass ('clicked'); // do stuff }});

The parent node acts as a dispatcher and can then do work based on what target Element
Triggered the event. If you find yourself binding one event listener
To export elements, you are doing something wrong (and slow ).

8. Eliminate query waste

Although jquery fails nicely if it does not find any matching
Elements, it still takes time to look for them. If you have one global
Javascript for your entire site, it may be tempting to throw every one
Of your jquery functions$ (Document). Ready (function () {// all my glorious code }).
Don't you dare. Only run functions that are applicable to the page.
The most efficient way to do this is to use inline Initialization
Functions so your template has full control over when and where
Javascript executes. For example, in your "article" page template, you
Wocould include the following code before the body close:

 
<SCRIPT type = "text/JavaScript> mylib. Article. INIT (); </SCRIPT> </body>

If your page template has des Any variety of modules that may or may
Not be on the page, or for visual reasons you need them to initialize
Sooner, you cocould place the initialization function immediately after
The module.

 
<Ul id = "traffic_light"> <li> <input type = "radio" class = "on" name = "light" value = "red"/> Red </LI> <li> <input type = "radio" class = "off" name = "light" value = "yellow"/> yellow </LI> <li> <input type =" radio "class =" off "name =" light "value =" green "/> green </LI> </ul> <SCRIPT type =" text/JavaScript> mylib. traffic_light.init (); </SCRIPT>

Your global JS library wocould look something like this:

 
VaR mylib = {article_page: {init: function () {// Article Page specific jquery functions .}}, traffic_light: {init: function () {// traffic light specific jquery functions .}}}

9. Defer $ (Window). Load

There is a temptation among jquery developers to hook everything into$ (Document). ReadyPseudo event. After all, it is used in most examples you will find. Although$ (Document). Ready
Is incredibly useful, it occurs during page render while objects are
Still downloading. If you notice your page stalling while loading, all
Those$ (Document). ReadyFunctions cocould be the reason why.
You can reduce CPU utilization during the page load by binding your
Jquery functions to$ (Window). LoadEvent, which occurs after all objects called by the HTML (including<IFRAME>Content) have downloaded.

 
$ (Window). Load (function () {// jquery functions to initialize after the page has loaded .});

Superfluous functionality such as drag and drop, binding visual
Effects and animations, pre-fetching hidden images, Etc., are all good
Candidates for this technique.

10. Compress Your JS

Okay, this isn' t jquery related, but I had to include it. There is
Tendency to make JavaScript Functions and variables overly descriptive,
Which is essential for developers but irrelevant to users. No more
Excuses, it's time to build JS compression into our workflows. Comment
The heck out of your code, and run it through a compression tool before
Launching to production. Use yuicompressor
To squeeze out wasteful bytes from your code. In our experience, it
Safely compresses JavaScript as small as it can possibly get without
CPU penalty (such as base62 encoding with packer ).Tip: for maximum compression in yuicompressor, always declare your variables (e.g. var my_long_variable_name ;).

11. Learn the library

Print out this jquery 1.3 cheat sheet,
and make it a goal to eventually understand what each function does. if
you find yourself repeating, there is probably an
easier (and more efficient) way.

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.