Home >Web Front-end >JS Tutorial >38 suggestions for jQuery performance optimization_jquery

38 suggestions for jQuery performance optimization_jquery

WBOY
WBOYOriginal
2016-05-16 16:57:06859browse

1. Pay attention to adding the var keyword when defining jQuery variables
This is not just jQuery, but also needs to be paid attention to in all javascript development processes. Please do not define it as follows:
$loading = $('#loading'); //This is a global definition. If you accidentally reference the same variable name somewhere, you will be depressed to death
2. Please use a var to define Variables
If you use multiple variables, please define them as follows:

Copy code The code is as follows:
var page = 0,
$loading = $('#loading'),
$body = $('body');

Don’t add it to every variable A var keyword, unless you have severe obsessive-compulsive disorder
3. Define jQuery variables by adding the $ symbol
When declaring or defining variables, please remember that if you are defining jQuery Variable, please add a $ sign in front of the variable, as follows:
Copy the code The code is as follows:
var $ loading = $('#loading');

The advantage of defining it like this is that you can effectively remind yourself or other users who read your code that this is a jQuery variable.
4. Please remember cache when operating DOM
In jQuery code development, we often need to operate DOM. DOM operation is a very resource-consuming process, and often many people Everyone likes to use jQuery like this:
Copy the code The code is as follows:

$('#loading' ).html('Complete');
$('#loading').fadeOut();

There is no problem with the code. You can also run it normally and get results, but be careful every time you define it. And when calling $('#loading'), a new variable is actually created. If you need to reuse it, remember to define it in a variable, so that the variable content can be effectively cached, as follows:
Copy code The code is as follows:
var $loading = $('#loading');
$loading. html('Finished');$loading.fadeOut();

This will provide better performance.
5. Use chain operations
For the above example, we can write it more concisely:
Copy code The code is as follows:

var $loading = $('#loading');
$loading.html('Complete').fadeOut();

6. Streamline jQuery code
Try to integrate some codes together, please do not code like this:
Copy Code The code is as follows:

//! ! Villain
$button.click(function(){
$target.css('width','50%');
$target.css('border','1px solid #202020' );
$target.css('color','#fff');
});

should be written like this:
Copy code The code is as follows:
$button.click(function(){
$target.css({'width':'50%','border ':'1px solid #202020','color':'#fff'});
});

7. Avoid using global type selectors
Do not write as follows: $('.something > *');
It is better to write like this: $('.something').children();
8. Do not overlap multiple IDs
Please do not write as follows: $('#something #children');
This is enough: $('#children');
9. Use more logical judgments || Or && to speed up
Do not write as follows:
Copy the code The code is as follows:

if(!$something) {
$something = $('#something ');
}

Writing performance is better this way:
Copy code The code is as follows:
$something= $something|| $('#something');

10. Try to use less code
Instead of writing like this: if(string.length > 0){..}
Write it like this: if(string.length) {..}
11. Try to use the .on method
If you use a newer version of the jQuery class library, please use .on. Any other methods will eventually use .on. to achieve.
12. Try to use the latest version of jQuery
The latest version of jQuery has better performance, but the latest version may not support ie6/7/8, so you need to adjust it according to the actual situation Situation selection.
13. Try to use native Javascript
If the functions provided by jQuery can also be implemented using native Javascript, it is recommended to use native javascript to achieve it.
14. Always inherit from the #id selector
This is a golden rule for jQuery selectors. The fastest way to select an element in jQuery is to select it by ID.
Copy code The code is as follows:
$('#content').hide();

Or inherit from the ID selector to select multiple elements:
Copy the code The code is as follows:
$('#content p').hide();

15. Use tag in front of class
The second fastest selector in jQuery is the tag selector (such as $('head')), because it comes directly from the native Javascript method getElementByTagName(). So it’s best to always use tags to modify classes (and don’t forget the nearest ID)
Copy code The code is as follows:
var receiveNewsletter = $('#nslForm input.on');

The class selector in jQuery is the slowest because it will traverse all DOM nodes under IE browser. Try to avoid using class selectors. Don't use tags to modify IDs either. The following example will traverse all div elements to find the node with the id 'content':
Copy the code The code is as follows:
var content = $('div#content'); // Very slow, don't use

Using ID to modify ID is superfluous:
Copy code The code is as follows:
var traffic_light = $('#content #traffic_light'); // Very slow, don’t use

16. Use subquery
to cache the parent object for future use

Copy code The code is as follows:
var header = $('#header');
var menu = header.find('.menu');
// or
var menu = $('.menu', header);

17. Optimize the selector with Applicable to Sizzle's "right-to-left" model
Since version 1.3, jQuery uses the Sizzle library, which is very different from the previous version in the way it behaves on the selector engine. It replaces the "right to left" model with a "left to right" model. Make sure the rightmost selector is specific and the left selector is broad:
Copy code The code is as follows:
var linkContacts = $('.contact-links div.side-wrapper');

instead of using
Copy code The code is as follows:
var linkContacts = $('a.contact-links .side-wrapper');

18. Use find( ), it is indeed faster to find the
.find() function without using context. But if a page has many DOM nodes, it may take more time to search back and forth:
Copy code The code is as follows:
var divs = $('.testdiv', '#pageBody'); // 2353 on Firebug 3.6
var divs = $('#pageBody').find('.testdiv'); // 2324 on Firebug 3.6 - The best time
var divs = $('#pageBody .testdiv'); // 2469 on Firebug 3.6

19. Write your own selector
If you often use selectors in your code, then extend jQuery’s $.expr[':'] object and write your own selector. In the following example, I created an abovethefold selector to select invisible elements:
Copy code The code is as follows:
$.extend($.expr[':'], {
abovethefold: function(el) {
return $(el).offset().top < $(window) .scrollTop() $(window).height();
}
});
var nonVisibleElements = $('div:abovethefold'); // Select element

20. Caching jQuery objects
Cache elements you frequently use:
Copy code The code is as follows :

var header = $('#header');
var divs = header.find('div');
var forms = header.find('form') ;

When DOM insertion is required, encapsulate all elements into one element

21. Direct DOM operation is very slow. Change the HTML structure as little as possible.

Copy code The code is as follows:

var menu = '';
$('#header').prepend(menu);
// Never do this:
$('#header'). prepend('');
for (var i = 1; i < 100; i ) {
$('#menu'). append('
  • ' i '
  • ');

    }
    22. Although jQuery does not throw exceptions, developers should also inspect objects

    Although jQuery will not throw a large number of exceptions to users, developers should not rely on this. jQuery usually executes a bunch of useless functions before determining whether an object exists. So before making a series of references to an object, you should first check whether the object exists.
    Twenty-three. Use direct functions instead of equivalent functions
    For better performance, you should use direct functions such as $.ajax() instead of Use $.get(), $.getJSON(), $.post(), because the latter ones will call $.ajax().
    24. Cache jQuery results for later use
    You will often get a javasript application object - you can use App. to save the objects you often select for future use Use:

    Copy code The code is as follows:

    App.hiddenDivs = $('div.hidden ');
    // Then call in your application:
    App.hiddenDivs.find('span');

    25. Use jQuery’s internal function data( ) to store the state
    Don’t forget to use the .data() function to store information:
    Copy code Code As follows:

    $('#head').data('name', 'value');
    // Then call it in your application:
    $('# head').data('name');

    26. Use jQuery utility function
    Don’t forget the simple and practical jQuery utility function. My favorites are $.isFunction(), $isArray() and $.each().
    Twenty-seven. Add the class "JS" to the HTML block
    When jQuery is loaded, first add a class called "JS" to the HTML
    Copy code The code is as follows:
    $('HTML').addClass('JS');

    Only when the user You can only add CSS styles when JavaScript is enabled. For example:
    Copy code 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 achieve what you want (for example: collapse certain panels or expand them when the user clicks on them). When Javascript is not enabled, the browser renders all content, and search engine crawlers will also remove all content. I will use this technique more in the future.
    28. Defer to $(window).load
    Sometimes $(window).load() is faster than $(document).ready() because the latter Executed before all DOM elements have been downloaded. You should test it before using it.
    29. Use Event Delegation
    When you have many nodes in a container and you want to bind an event to all nodes, delegation is very suitable for such application scenarios. Using Delegation, we only need to bind the event at the parent and then see which child node (target node) triggered the event. This becomes very convenient when you have a table with a lot of data and you want to set events on the td node. First get the table, and then set delegation events for all td nodes:
    Copy code The code is as follows:
    $ ("table").delegate("td", "hover", function(){
    $(this).toggleClass("hover");
    });

    30. Use the abbreviation of ready event
    If you want to compress the js plug-in and save every byte, you should avoid using $(document).onready()
    Copy code The code is as follows:
    // Do not use
    $(document).ready(function (){
    // Code
    });
    // You can abbreviate it like this:
    $(function (){
    // Code
    });

    31. jQuery Unit Testing
    The best way to test JavaScript code is to have people test it. But you can use some automated tools such as Selenium, Funcunit, QUit, QMock to test your code (especially plug-ins). I want to discuss this topic in another topic because there is so much to say.
    ThreeTwelve. Standardize your jQuery code
    Standardize your code often to see which query is slower and replace it. You can use the Firebug console. You can also use jQuery's shortcut functions to make testing easier:
    Copy the code The code is as follows:

    // Shortcut to record data in Firebug console
    $.l($('div'));

    // Get UNIX timestamp
    $.time();

    // Record code execution time in Firebug
    $.lt();
    $('div');
    $.lt();

    // Put the code block in a for loop to test the execution time
    $.bm("var divs = $('.testdiv', '#pageBody');"); // 2353 on Firebug 3.6


    33. Use HMTL5
    The new HTML5 standard brings a lighter DOM structure. A lighter structure means fewer traversals are required when using jQuery, and better loading performance. So please use HTML5 if possible.
    34. If you want to add styles to more than 15 elements, add style tags directly to the DOM elements
    To add styles to a few elements, the best way is to use jQuey css() function. However, when adding styles to more than 15 elements, it is more effective to add style tags directly to the DOM. This method avoids using hard code in the code.
    Copy code The code is as follows:

    $('')
    .appendTo('head');

    35. Avoid loading redundant code
    It is a good idea to put Javascript code in different files and load them only when needed. This way you won't load unnecessary code and selectors. It is also easy to manage code.
    36. Compress into one main JS file and keep the number of downloads to a minimum
    When you have determined which files should be loaded, package them into one file . Use some open source tools to automatically do it for you, such as using Minify (integrated with your back-end code) or using online tools such as JSCompressor, YUI Compressor or Dean Edwards JS packer to compress files for you. My favorite is JSCompressor.
    37. Use native Javascript when needed
    Using jQuery is a great thing, but don’t forget that it is also a framework for Javascript. So you can use native Javascript functions when necessary in jQuery code, which can achieve better performance.
    38. Lazy load content for speed and SEO benefits not only improves loading speed, but also improves SEO optimization (Lazy load content for speed and SEO benefits)
    Use Ajax to load your website Well, this can save server-side loading time. You can start with a common sidebar widget.
    Statement:
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn