38 suggestions for jQuery performance optimization _ jquery

Source: Internet
Author: User
Presumably everyone is familiar with jQuery, the most popular javascript class library, and as long as it is a front-end developer, it must have been more or less used or used. In this article, based on some materials and practical usage efficiency, I will introduce some principles for writing high-quality jQuery code. It will not only tell you how to write, but also tell you why to write like this, I hope you will find it helpful. 1. Add the var keyword when defining jQuery variables.
This is not just jQuery. It should be noted in all javascript development processes. Please do not define it as follows:
$ Loading = $ ('# loading'); // This is a global definition. If you do not know where the same variable name is referenced, it will be depressing.
Ii. Use a var to define variables
If you use multiple variables, define them as follows:

The Code is as follows:

Var page = 0,
$ Loading = $ ('# loading '),
$ Body = $ ('body ');


Do not add a var keyword to every variable unless you have serious obsessive-compulsive disorder.
3. Define the jQuery variable to add the $ symbol
When declaring or defining a variable, remember to add a $ symbol before the variable if you are defining the jQuery variable, as shown below:

The Code is as follows:

Var $ loading = $ ('# loading ');


The benefit is that you can effectively prompt yourself or other users who read your code. This is a jQuery variable.
4. Remember to cache DOM operations)
In jQuery code development, we often need to operate the DOM. DOM operations are a process that consumes a lot of resources, and many people usually like to use jQuery like this:

The Code is as follows:


Certificate ('{loading'{.html ('complete ');
$ ('# Loading'). fadeOut ();


The Code does not have any problems, and you can run the results normally, but note that each time you define and call $ ('# loading'), a new variable is actually created, if you need to reuse the variable, remember to define it into a variable. This effectively caches the variable content as follows:

The Code is as follows:

Var $ loading = $ ('# loading ');
Uploloading.html ('complete'); $ loading. fadeOut ();


This will provide better performance.
5. Use chained operations
In the example above, we can write more concisely:

The Code is as follows:


Var $ loading = $ ('# loading ');
Uploloading.html ('complete'). fadeOut ();


Vi. Simplified jQuery code
Try to integrate some code together. Do not encode it like this:

The Code is as follows:


//!! Negative
$ Button. click (function (){
Define target.css ('width', '123 ');
Using target.css ('border', '1px solid #202020 ');
Define target.css ('color', '# fff ');
});


It should be written as follows:

The Code is as follows:

$ Button. click (function (){
Export target.css ({'width': '000000', 'border': '1px solid # 000000', 'color': '# fff '});
});


7. Avoid using global Selector
Do not write as follows: $ ('. something> *');
It is better to write: $ ('. something'). children ();
8. Do not add multiple IDs.
Do not write as follows: $ ('# something # children ');
This is enough: $ ('# children ');
9. Multi-Purpose logic judgment | or & to speed up
Do not write as follows:

The Code is as follows:


If (! $ Something ){
$ Something = $ ('# something ');
}


The writing performance is better:

The Code is as follows:

$ Something = $ something | $ ('# something ');


10. Try to use less code
Write it like this: if (string. length> 0 ){..}
It is better to write as follows: if (string. length ){..}
11. Try to use the. on Method
If you use a newer version of The jQuery class library, use. on. Any other method is implemented using. on.
12. Use the latest jQuery version whenever possible.
The latest version of jQuery has better performance, but the latest version may not support ie6/7/8, so you need to choose your own based on the actual situation.
13. Try to use native Javascript
If you can use native Javascript to implement the functions provided by jQuery, we recommend that you use native javascript.
14. 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 ();


15. 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


16. 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 );


17. Optimize the selector to apply the "from right to left" model of Sizzle
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 ');


18. 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


19. 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


20. 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 ');

When DOM insertion is required, all elements are encapsulated into one element.

21. 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 +'
  • ');


    }
    22. 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.
    23. Use direct functions instead of functions equivalent
    For better performance, you should use direct functions such as $. ajax () instead of $. get (), $. getJSON (), $. post (), because the next few will call $. ajax ().
    24. 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 ');


    25. 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 ');


    26. Use the jQuery utility Function
    Don't forget the simple and practical jQuery utility function. What I like most is $. isFunction (), $ isArray (), and $. each ().
    . Add "JS" class for 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.
    Twenty-eight, postponed to $ (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.
    29. 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 ");
    });


    Thirty. 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
    });


    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.
    3.12. 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 '));

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

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

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


    33. 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.
    . 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 ');


    35. 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.
    . Compress the file into a main JS file, keeping 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.
    . 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.
    Slow loading of content not only improves loading speed, but also improves SEO optimization (Lazy load content for speed and SEO benefits)
    Use Ajax to load your website, which can save loading time on the server. You can start with a common sidebar widget.

    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.