search
HomeWeb Front-endJS Tutorial28 suggestions for jQuery performance optimization that you should learn from_jquery

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 }
});
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 $('#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를 사용하여 웹사이트를 로드하면 서버 측 로딩 시간이 절약됩니다. 일반적인 사이드바 위젯으로 시작할 수 있습니다.
    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
    Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

    Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

    From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

    The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

    JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

    Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

    Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

    JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

    Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

    I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

    How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

    This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

    JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

    JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

    The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

    The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    WWE 2K25: How To Unlock Everything In MyRise
    1 months agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    Safe Exam Browser

    Safe Exam Browser

    Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

    SublimeText3 Linux new version

    SublimeText3 Linux new version

    SublimeText3 Linux latest version

    MantisBT

    MantisBT

    Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

    WebStorm Mac version

    WebStorm Mac version

    Useful JavaScript development tools