


28 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.
$('#content').hide();
Or inherit from the ID selector to select multiple elements:
$('#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)
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':
var content = $('div#content'); // Very slow, don’t use
Using ID to modify ID is superfluous:
var traffic_light = $('#content #traffic_light'); // Very slow, Do not use
3. Use subquery
to cache the parent object for future use
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:
var linkContacts = $('.contact-links div.side-wrapper');
instead of using
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:
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:
$('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:
$.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:
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.
var menu = ' ';
$('#header').prepend(menu);
// Never do this:
$('#header').prepend(' ');
for (var i = 1; i $('#menu').append('
}
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:
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:
$( '#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
$('HTML').addClass('JS');
Only when the user enables JavaScript , you can add CSS styles. For example:
/* 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:
$("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()
// 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:
// 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
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.
$('')
.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"> 🎜>
Ajax를 사용하여 웹사이트를 로드하면 서버 측 로딩 시간이 절약됩니다. 일반적인 사이드바 위젯으로 시작할 수 있습니다.

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.

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.

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.

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.

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

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

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 latest version

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
Useful JavaScript development tools