28 suggestions for jQuery performance optimization _ jquery

Source: Internet
Author: User
I have been searching for tips on jQuery performance optimization to make my bloated dynamic web page application lighter. I decided to list some of the best and most commonly used performance optimization suggestions, if you are interested, don't miss it. Maybe the suggestions provided in this article will help you with jQuery performance optimization. 28 suggestions have been searching for tips on jQuery performance optimization, it makes my bloated dynamic web application lighter. After finding many articles, I decided to list some of the best and most commonly used performance optimization suggestions. I also made a concise jQuery performance-optimized style sheet, which can be printed out or set as a desktop background.
I. selector performance optimization suggestions
1. always inherit from the # id Selector
This is a golden rule of jQuery selector. The fastest way for jQuery to select an element is to use ID.

The Code is as follows:


$ ('# Content'). hide ();


You can also select multiple elements from the ID selector:

The Code is as follows:


$ ('# Content p'). hide ();


2. Use tags before the class
In jQuery, the second-fastest selector is the tag selector (such as $ ('head'), because it is directly from the native Javascript method getElementByTagName (). So it is best to always use tags to modify the class (and do not forget the nearest ID)

The Code is as follows:


Var incluenewsletter =ter ('# nslForm input. on ');


In jQuery, the class selector is the slowest, because in IE browser, it traverses all DOM nodes. Avoid using the class selector whenever possible. Do not use tags to modify the ID. The following example traverses all p elements to find the node with the id of 'content:

The Code is as follows:


Var content = $ ('P # content'); // very slow, do not use


Using ID to modify the ID is also superfluous:

The Code is as follows:


Var traffic_light = $ ('# content # traffic_light'); // very slow, do not use


3. Use subquery
Cache the parent object for future use

The Code is as follows:


Var header = $ ('# header ');
Var menu = header. find ('. menu ');
// Or
Var menu = $ ('. menu', header );


4. optimized the selector to apply the Sizzle "from right to left" model.
Since version 1.3, jQuery has adopted the Sizzle library, which is very different from the previous version in the selector engine. It uses the "from left to right" model to replace the "from right to left" model. Make sure that the rightmost selector is specific, and the left selector has a wider range of options:

The Code is as follows:


Var linkContacts = $ ('. contact-links p. side-wrapper ');


Do not use

The Code is as follows:


Var linkContacts = $ ('A. contact-links. side-wrapper ');


5. Use find () instead of context search
The. find () function is indeed faster. However, if a page has many DOM nodes and needs to be searched back and forth, it may take more time:

The Code is as follows:


Var ps = $ ('. testp',' # pageBody '); // 2353 on Firebug 3.6
Var ps = $ ('# pagebody'). find ('. testp'); // 2324 on Firebug 3.6-The best time
Var ps = $ ('# pageBody. testp'); // 2469 on Firebug 3.6


6. Use powerful chain operations
The chain operation using jQuery is more effective than the cache selector:

The Code is as follows:


$ ('Li. menu-item'). click (function () {alert ('test click ');})
. Css ('display', 'block ')
. Css ('color', 'red ')
FadeTo (2, 0.7 );


7. compile your Selector
If you often use selector in code, extend the $. expr [':'] object of jQuery and write your own selector. In the following example, I created an abovethefold selector to select invisible elements:

The Code is as follows:


$. Extend ($. expr [':'], {
Abovethefold: function (el ){
Return $ (el). offset (). top <$ (window). scrollTop () + $ (window). height ();
}
});
Var nonVisibleElements = $ ('P: abovethefold'); // select an element


Ii. DOM optimization suggestions
8. cache jQuery objects
Cache frequently used elements:

The Code is as follows:


Var header = $ ('# header ');
Var ps = header. find ('P ');
Var forms = header. find ('form ');


9. When DOM insertion is required, all elements are encapsulated into one element.
Direct DOM operations are slow. Change the HTML structure as little as possible.

The Code is as follows:


Var menu ='

    ';
    For (var I = 1; I <100; I ++ ){
    Menu + ='
  • '+ I +'
  • ';
    }
    Menu + ='
';
$ ('# Head'). prepend (menu );
// Do not do this:
$ ('# Head'). prepend ('
    ');
    For (var I = 1; I <100; I ++ ){
    $ ('# Menu'). append ('
  • '+ I +'
  • ');
    }


    10. Although jQuery does not throw an exception, developers should also check the object
    Although jQuery does not throw a large number of exceptions to users, developers should not rely on this. JQuery usually runs a lot of useless functions to determine whether an object exists. Therefore, before making a series of references to an object, check that the object does not exist.
    11. Use direct functions instead of functions equivalent to them.
    For better performance, you should use direct functions such as $. ajax () instead of $. get (), $. getJSON (), $. post (), because the next few will call $. ajax ().
    12. cache jQuery results for future use
    You will often get an javasript Application Object-you can use the App to save the objects you have selected for future use:

    The Code is as follows:


    App. hiddenDivs = $ ('p. Den den ');
    // Call the following in your application:
    App. hiddenDivs. find ('span ');


    13. Use jQuery's internal function data () to store the status
    Do not forget to use the. data () function to store information:

    The Code is as follows:


    $ ('# Head'). data ('name', 'value ');
    // Call the following in your application:
    $ ('# Head'). data ('name ');


    14. Use the jQuery utility Function
    Don't forget the simple and practical jQuery utility function. What I like most is $. isFunction (), $ isArray (), and $. each ().
    15. Add "JS" class to HTML Blocks
    After jQuery is loaded, add a class named "JS" to HTML.

    The Code is as follows:


    $ ('Html '). addClass ('js ');


    You can add CSS styles only when you enable JavaScript. For example:

    The Code is as follows:


    /* In css */
    . JS # myDiv {display: none ;}


    So when JavaScript is enabled, you can hide the entire HTML content and use jQuery to implement what you want (for example, collapse some panels or expand when users click them ). When Javascript is not enabled, the browser displays all the content, and the search engine crawler also hooks up all the content. I will use this technique more in the future.
    Iii. Suggestions on optimizing event Performance
    16. delay until $ (window). load
    Sometimes $ (window). load () is faster than $ (document). ready (), because the latter does not run until all DOM elements are downloaded. You should test it before using it.
    17. Use Event Delegation
    When you have many nodes in a container and want to bind an event to all nodes, delegation is suitable for such application scenarios. When using Delegation, we only need to bind events at the parent level, and then check which child node (target node) triggers the event. When you have a table with a lot of data, you want to set events for the td node, which is very convenient. First obtain the table, and then set the delegation event for all td nodes:

    The Code is as follows:


    $ ("Table"). delegate ("td", "hover", function (){
    $ (This). toggleClass ("hover ");
    });


    18. Use the abbreviation of ready event
    If you want to compress the js plug-in to save every byte, you should avoid using $ (document). onready ()

    The Code is as follows:


    // Do not use
    $ (Document). ready (function (){
    // Code
    });
    // You Can abbreviated it as follows:
    $ (Function (){
    // Code
    });


    Iv. Test jQuery
    19. jQuery unit test
    The best way to test the JavaSript code is to test it by yourself. However, you can use automated tools such as Selenium, Funcunit, QUit, and QMock to test your code (especially plug-ins ). I want to discuss this topic in another topic because there are too many things to talk about.
    20. Standardize your jQuery code
    You often standardize your code to see which query is slow and then replace it. You can use the Firebug console. You can also use jQuery's shortcut functions to make testing easier:

    The Code is as follows:


    // A shortcut for recording data in the Firebug Console
    $. L ($ ('P '));


    The Code is as follows:


    // Obtain the UNIX Timestamp
    $. Time ();


    The Code is as follows:


    // Record the code execution time in Firebug
    $. Lt ();
    $ ('P ');
    $. Lt ();


    The Code is as follows:


    // Place the code block in a for loop to test the execution time
    $. Bm ("var ps = $ ('. testp',' # pageBody ');"); // 2353 on Firebug 3.6


    5. Other common jQuery performance optimization suggestions
    21. Use the latest version of jQuery
    The latest version is often the best. After changing the version, do not forget to test your code. Sometimes it is not completely backward compatible.
    22. Use HMTL5
    The new HTML5 standard provides a lightweight DOM structure. A lighter structure means that jQuery requires less traversal and better loading performance. So use HTML5 if possible.
    23. if you add a style to more than 15 elements, add the style label to the DOM element directly.
    The best way to add styles to a few elements is to use the jQuey css () function. However, it is more effective to directly add the style label to the DOM when more than 15 elements add styles. This method avoids hard code ).

    The Code is as follows:


    $ ('')
    . AppendTo ('head ');


    24. Avoid loading unnecessary code
    It is a good way to put Javascript code in different files. Load them only when necessary. In this way, you will not load unnecessary code and selectors. It also facilitates code management.
    25. compress the file into a main JS file to keep the download count to a minimum
    When you have determined which files should be loaded, package them into a file. You can use some open-source tools to automatically compress your files, such as Minify (integrated with your back-end Code) or JSCompressor, YUI Compressor or Dean Edwards JS packer. My favorite is JSCompressor.
    26. Use the native Javasript when necessary
    Using jQuery is a great thing, but don't forget that it is also a Javascript framework. Therefore, you can use native Javascript Functions when jQuery code is necessary to achieve better performance.
    27. Load the jQuery framework from Google
    When your application is officially launched, load jQuery from Google CDN because you can get code from the nearest place. In this way, you can reduce server requests. If a user browses other websites and uses Google CDN's jQuery, the browser immediately calls out the jQuery code from the cache.

    The Code is as follows:


    // Link the compressed code of a specific version

    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.