Home > Web Front-end > JS Tutorial > body text

28 suggestions for jQuery performance optimization that you should learn from_jquery

WBOY
Release: 2016-05-16 17:41:43
Original
1079 people have browsed it

28 Suggestions for jQuery Performance Optimization I have been looking for tips on jQuery performance optimization to make my bloated dynamic web application lighter. After searching many articles, I decided to list some of the best and most commonly used suggestions for optimizing performance. I also made a concise jQuery performance-optimized stylesheet that you can print or set as your desktop background.
1. Selector performance optimization suggestions
1. 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 code The code is as follows:

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

2. Use tag in front of class
The second fastest selector in jQuery is 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 under IE browser it will traverse all DOM node. 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 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, Do not use

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

4. Optimize the selector to adapt to Sizzle's "right to left" model
Since version 1.3, jQuery The Sizzle library is used, which is very different from the previous version's representation 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');

5. Use find() instead of context search
.find() function is indeed faster. 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

6. Take advantage of powerful chains Type operation
using jQuery’s chain operation is more efficient than caching selectors:
Copy code The code is as follows:

$('li.menu-item').click(function () {alert('test click');})
.css('display', 'block')
.css('color', 'red')
fadeTo(2, 0.7);

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

2. Suggestions for optimizing DOM operations
8. Cache 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');

9. When DOM insertion is to be performed, encapsulate all elements into one element
Direct DOM operations are 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 '
  • ');
    }

    10. Although jQuery does not throw exceptions, developers should also check objects
    Although jQuery A large number of exceptions will not be thrown to users, but 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.
    11. Use direct functions instead of equivalent functions
    For better performance, you should use direct functions like $.ajax() instead of $.get(),$ .getJSON(),$.post(), because the latter ones will call $.ajax().
    12. Cache jQuery results for later use
    You will often get a javascript application object - you can use App. to save the objects you often select for future use:
    Copy code The code is as follows:

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

    13. Use jQuery’s internal function data() to store the state
    Don’t forget Use the .data() function to store information:
    Copy code The code is as follows:

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

    14. Use jQuery utility functions
    Don’t forget the simple and practical jQuery utility functions. My favorites are $.isFunction(), $isArray() and $.each().
    15. Add the "JS" class to the HTML block
    After 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 enables JavaScript , you can add CSS styles. 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.
    3. Suggestions on optimizing event performance
    16. Defer to $(window).load
    Sometimes $(window).load() is used instead of $(document). ready() is faster because the latter does not wait until all DOM elements have been downloaded. You should test it before using it.
    17. 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 obtain 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");
    });

    18. Use the abbreviation of ready event
    If you want to compress the js plugin 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 shorten it like this:
    $(function (){
    // Code
    });

    4. Testing jQuery
    19. 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.
    20. 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'));

    Copy code The code is as follows:

    // Get UNIX timestamp
    $.time();

    Copy code The code is as follows:

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

    Copy code The code is as follows:

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

    5. Other common jQuery performance optimization suggestions
    21. Use the latest version of jQuery
    The latest version Often the best. After changing versions, don't forget to test your code. Sometimes it's not completely backwards compatible.
    22. Using 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.
    23. 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's 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');

    24. 중복된 코드 로딩을 ​​피하세요
    Javascript 코드를 다른 파일에 넣어 필요할 때만 로딩하는 것이 좋습니다. 이렇게 하면 불필요한 코드와 선택기를 로드하지 않아도 됩니다. 코드 관리도 쉽습니다.
    25. 다운로드 수를 최소화하기 위해 하나의 기본 JS 파일로 압축합니다.
    로드해야 할 파일을 결정한 후 하나의 파일로 패키지합니다. Minify(백엔드 코드와 통합)를 사용하거나 JSCompressor, YUI Compressor 또는 Dean Edwards JS 패커와 같은 온라인 도구를 사용하여 파일을 압축하는 등 일부 오픈 소스 도구를 사용하여 자동으로 수행할 수 있습니다. 내가 가장 좋아하는 것은 JSCompressor입니다.
    26. 필요할 때 기본 Javascript를 사용하세요
    jQuery를 사용하는 것은 좋은 일이지만 이것이 Javascript를 위한 프레임워크이기도 하다는 사실을 잊지 마세요. 따라서 jQuery 코드에서 필요할 때 기본 Javascript 함수를 사용하면 더 나은 성능을 얻을 수 있습니다.
    27. Google에서 jQuery 프레임워크 로드
    애플리케이션이 공식적으로 출시되면 사용자가 가장 가까운 곳에서 코드를 얻을 수 있으므로 Google CDN에서 jQuery를 로드하세요. 이렇게 하면 서버 요청을 줄일 수 있으며, 사용자가 Google CDN의 jQuery를 사용하는 다른 웹사이트를 탐색하는 경우 브라우저는 즉시 캐시에서 jQuery 코드를 호출합니다.
    코드 복사 코드는 다음과 같습니다.

    // 압축 코드의 특정 버전 링크
    < ;script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"> 🎜>
    28. 속도 및 SEO 이점을 위한 지연 로드 콘텐츠(속도 및 SEO 이점을 위한 지연 로드 콘텐츠)
    Ajax를 사용하여 웹사이트를 로드하면 서버 측 로딩 시간이 절약됩니다. 일반적인 사이드바 위젯으로 시작할 수 있습니다.
    Related labels:
    source:php.cn
    Statement of this Website
    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
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template