Sometimes when we write jQuery, for the convenience of writing code, we often ignore the pressure brought to the client during program execution. Along with this comes problems such as slow running speed or even inability to run on some low-end browsers or low-end computers.
Therefore, it is necessary for us to optimize our own jquery code to achieve faster and smoother operation.
Advanced techniques for jquery performance optimization. The following mainly introduces jquery performance optimization from seven aspects:
1. Introduce jQuery library through CDN (Content Delivery Network)
2. Reduce DOM operations
3. Use native JS appropriately
4. Selector optimization
5. Caching jQuery objects
6. Define a reusable function
7. Use array method to traverse jQuery object collection
The specific instructions for each method are explained below:
Introducing the jQuery library through CDN (Content Delivery Network)
The simplest step to improve the performance of JavaScript in your website is to introduce the latest version of the jQuery library. The newly released version usually has better performance improvements and fixes some bugs. Or introducing it through CDN is also a good choice. Introduction through CDN can reduce the loading time of the website.
Here are some CDN services:
<!-- Case 1 - jQuery CDN --> <script src="http://code.jquery.com/jquery-1.10.2.min.js" ></script> <!-- Case 2 - requesting jQuery from Googles CDN (notice the protocol) --> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script> <!-- Case 3 - requesting the latest minor 1.10.x version (only cached for an hour) --> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10/jquery.min.js" ></script> <!-- Case 4 - requesting the absolute latest jQuery version (use with caution) --> <script src="http://code.jquery.com/jquery.min.js" ></script>
Some domestic CDN services:
http://www.bootcdn.cn/jquery/ <!--新浪 CDN--> <script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script> <!--百度 CDN--> <script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script> <!--Bootstrap CDN--> http://www.bootcdn.cn/jquery/
Reduce DOM operations
Although JavaScript performance has been greatly improved, DOM operations are still very resource-intensive, and DOM operations need to be reduced. This is especially important when inserting a large number of elements into a page.
For example:
<div id="elem" ></div> // 不好的方式 //var elem = $('#elem'); //for(var i = 0; i < 100; i++){ // elem.append('<li>element '+i+'</li>'); //} // 好的方式 var elem = $('#elem' ), arr = []; for(var i = 0; i < 100; i++){ arr. push('<li>element ' +i+'</li>' ); } elem. append(arr. join('' ));
Caching all elements and inserting them once will improve performance because only one redraw of the page is triggered. The same is true for CSS style properties.
More reading: Front-end page stuck? It may be caused by DOM operations, you need to optimize the code
Use native JS appropriately
Creating jQuery objects brings some overhead. Therefore, if performance is more important, use native javascript as much as possible. In some ways it might be easier to understand and require less code to write. For example:
// 打印list中的li的id $('#colors li' ). each(function(){ //将$(this).attr('id')方法替换为直接通过ID属性访问 console. log(this. id); })
Selector Optimization
If you need better performance but still want to use jQuery, you can try some jQuery selector optimization. The following is a test program that records the execution time of different selectors through the browser's console console.time and console.timeEnd methods.
HTML:
<div id="peanutButter" > <div id="jelly" class=".jellyTime" ></div> </div> JS: //测试程序 var iterations = 10000, i; //-------------------------------------------- //Case 1: 很慢 console.time('Fancy'); for (i = 0; i < iterations; i++) { $('#peanutButter div:first'); } console.timeEnd('Fancy'); //-------------------------------------------- //Case 2: 比较好,但仍然很慢 console.time('Parent-child'); for (i = 0; i < iterations; i++) { $('#peanutButter div'); } console.timeEnd('Parent-child'); //-------------------------------------------- //Case 3: 一些浏览器会比较快 console.time('Parent-child by class'); for (i = 0; i < iterations; i++) { // 通过后代Class选择器 $('#peanutButter .jellyTime'); } console.timeEnd('Parent-child by class'); //-------------------------------------------- //Case 4: 更好的方式 console.time('By class name'); 21 for (i = 0; i < iterations; i++) { // 直接通过Class选择器 $('.jellyTime'); } console.timeEnd('By class name'); //-------------------------------------------- //Case 5: 推荐的方式 ID选择器 console.time('By id'); for (i = 0; i < iterations; i++) { $('#jelly'); } console.timeEnd('By id');
Execution result:
Caching jQuery objects
Every time a new jQuery object is constructed through a selector, the Sizzle engine at the core of jQuery will traverse the DOM and match the real dom element through the corresponding selector. This method is relatively inefficient. In modern browsers, you can use the document.querySelector method to match the corresponding element by passing in the corresponding Class parameter. However, versions below IE8 do not support this method. One practice to improve performance is to cache jQuery objects via variables. For example:
<ul id="pancakes" > <li>first</li> <li>second</li> <li>third</li> <li>fourth</li> <li>fifth</li> </ul>
JS:
// 不好的方式: // $('#pancakes li').eq(0).remove(); // $('#pancakes li').eq(1).remove(); // $('#pancakes li').eq(2).remove(); // ------------------------------------ // 推荐的方式: var pancakes = $('#pancakes li'); pancakes.eq(0).remove(); pancakes.eq(1).remove(); pancakes.eq(2).remove(); // ------------------------------------ // 或者: // pancakes.eq(0).remove().end() // .eq(1).remove().end() // .eq(2).remove().end();
Define a reusable function
Go directly to the example:
HTML: <button id="menuButton" >Show Menu!</button> <a href="#" id="menuLink" >Show Menu!</a>
JS:
//Bad: //这个会导致多个回调函数的副本占用内存 $('#menuButton, #menuLink' ). click(function(){ // ... }); //---------------------------------------------- //Better function showMenu(){ alert('Showing menu!' ); // Doing something complex here } $('#menuButton' ). click(showMenu); $('#menuLink' ). click(showMenu);
If you define an inline callback function with a jQuery object containing multiple elements (as in the first example above), a callback function will be saved in memory for each element in the collection. copy of.
Use array method to traverse jQuery object collection
You may not have noticed, but this elegant implementation of the jQuery each method comes at a cost in terms of performance. There is a faster way to iterate over a jQuery object. It is implemented through an array. The jQuery object collection is an array-like object with length and value attributes. You can test the performance through the program:
HTML:
<ul id="testList" > <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <!-- add 50 more --> </ul>
JS:
var arr = $('li'), iterations = 100000; //------------------------------ // Array实现: console.time('Native Loop'); for (var z = 0; z < iterations; z++) { var length = arr.length; for (var i = 0; i < length; i++) { arr[i]; } } console.timeEnd('Native Loop'); //------------------------------ // each实现: console.time('jQuery Each'); for (z = 0; z < iterations; z++) { arr.each(function(i, val) { this; }); } console.timeEnd('jQuery Each');
Result:
You can see that traversal through array implementation has higher execution efficiency.
//------------------------------------------------ -------Continuous updates...
The above is a summary of some collected knowledge. If you have any suggestions or questions, please leave a message for discussion.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version
SublimeText3 Linux latest version

Notepad++7.3.1
Easy-to-use and free code editor

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
