jQuery code optimization traversal_jquery
After understanding the working mechanism behind jQuery's DOM traversal, you can consciously avoid unnecessary repeated operations when writing code, thereby improving the performance of the code. This article will briefly discuss the issue of optimizing jQuery code starting from jQuery's traversal mechanism.
jQuery object stack
jQuery internally maintains a jQuery object stack. Each traversal method finds a new set of elements (a jQuery object), and jQuery pushes the set of elements onto the stack. Each jQuery object has three attributes: context, selector, and prevObject. The prevObject attribute points to the previous object in the object stack, and through this attribute, you can go back to the original set of DOM elements.
jQuery provides two very useful methods for us to operate this internal object stack:
.end()
.andSelf()
Calling the first method is simply pops up an object (resulting in a return to the previous jQuery object). The second method is more interesting. Calling it will backtrack a position in the stack, then combine the element sets at the two positions, and push the new, combined element set to the top of the stack.
Using this DOM element stack can reduce repeated query and traversal operations, and reducing repeated operations is the key to optimizing jQuery code performance.
Optimization example
The following is a function (the front and rear codes are omitted) to achieve the table row stripe effect:
function stripe() {
$('#news').find('tr.alt').removeClass ('alt');
$('#news tbody').each(function() {
$(this).children(':visible').has('td')
. filter(':group(3)').addClass('alt');
});
}
The stripe() function uses the ID selector twice #news Find elements: once to remove the alt class from rows with that class, and once to add the class to newly selected rows.
There are two ways to optimize this function, one is concatenation.
Concatenation
Concatenation optimization utilizes jQuery’s internal object stack and .end() method. The optimized code is as follows:
function stripe() {
$('#news').
find('tr.alt').removeClass('alt').end()
find('tbody').each(function() {
$(this).children(':visible').has('td')
.filter(':group(3)').addClass('alt');
});
}
The first call to .find() will push the table rows onto the stack, and then the .end() method will pop these rows out, allowing the next call to .find() Still performing operations on the #news table. This reduces two selector searches to one.
Another optimization method is caching.
Caching
The so-called cache here is to save the results of previous operations for reuse in the future. The optimized code is as follows:
var $news = $( '#news');
function stripe() {
$news.find('tr.alt').removeClass('alt');
$news.find('tbody').each (function() {
$(this).children(':visible').has('td')
.filter(':group(3)').addClass('alt');
});
}
Compared with the concatenated method, the caching method is a little more verbose because an additional variable is created to save the jQuery object. But from another perspective, this method can completely separate the two operations on the selected element in the code, which may meet our needs in other situations. Similarly, because the selected elements can be saved outside the stripe() function, it avoids the need to repeatedly query the selector each time the function is called.
Conclusion
Using jQuery’s internal object stack and cache can reduce repeated DOM queries and traversals, thereby improving script execution speed.
Because selecting elements in the page based on ID is extremely fast, there will be no obvious performance difference between the above two examples before and after optimization. In actual coding, you should choose the method that is the most readable and easiest to maintain. If you really encounter a performance bottleneck, the above optimization techniques can have immediate results.
(Note: This article is based on the relevant chapters of "JQuery Basics Tutorial (3rd Edition)".)

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

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Java is a popular programming language with powerful file handling capabilities. In Java, traversing a folder and getting all file names is a common operation, which can help us quickly locate and process files in a specific directory. This article will introduce how to implement a method of traversing a folder and getting all file names in Java, and provide specific code examples. 1. Use the recursive method to traverse the folder. We can use the recursive method to traverse the folder. The recursive method is a way of calling itself, which can effectively traverse the folder.

As one of the most popular programming languages in the world, Java has become the language of choice for many businesses and developers. However, code refactoring is crucial to maintaining code quality and development efficiency. Java code can become increasingly difficult to maintain over time due to its complexity. This article will discuss how to refactor Java code to improve code quality and maintainability. Understand the principles of refactoring The purpose of Java code refactoring is to improve the structure, readability and maintainability of the code, rather than simply "changing the code". because

Example of using PHPglob() function: Traverse all files in a specified folder In PHP development, it is often necessary to traverse all files in a specified folder to implement batch operation or reading of files. PHP's glob() function is used to achieve this requirement. The glob() function can obtain the path information of all files that meet the conditions in the specified folder by specifying a wildcard matching pattern. In this article, we will demonstrate how to use the glob() function to iterate through all files in a specified folder

Code optimization techniques in PHP high concurrency processing With the rapid development of the Internet, high concurrency processing has become an important issue in web application development. In PHP development, how to optimize code to cope with high concurrent requests has become a difficult problem that programmers need to solve. This article will introduce some code optimization techniques in PHP high concurrency processing, and add code examples to illustrate. Reasonable use of cache For high concurrency situations, frequent access to the database will lead to excessive system load and relatively slow access to the database. Therefore, we can

Program performance optimization methods include: Algorithm optimization: Choose an algorithm with lower time complexity and reduce loops and conditional statements. Data structure selection: Select appropriate data structures based on data access patterns, such as lookup trees and hash tables. Memory optimization: avoid creating unnecessary objects, release memory that is no longer used, and use memory pool technology. Thread optimization: identify tasks that can be parallelized and optimize the thread synchronization mechanism. Database optimization: Create indexes to speed up data retrieval, optimize query statements, and use cache or NoSQL databases to improve performance.

1. Code optimization to avoid using too many security annotations: In Controller and Service, try to reduce the use of @PreAuthorize and @PostAuthorize and other annotations. These annotations will increase the execution time of the code. Optimize query statements: When using springDataJPA, optimizing query statements can reduce database query time, thereby improving system performance. Caching security information: Caching some commonly used security information can reduce the number of database accesses and improve the system's response speed. 2. Use indexes for database optimization: Creating indexes on tables that are frequently queried can significantly improve the query speed of the database. Clean logs and temporary tables regularly: Clean logs and temporary tables regularly

Conceptual differences: Iterator: Iterator is an interface that represents an iterator that obtains values from a collection. It provides methods such as MoveNext(), Current() and Reset(), allowing you to traverse the elements in the collection and operate on the current element. Iterable: Iterable is also an interface, representing an iterable object. It provides the Iterator() method, which returns an Iterator object to facilitate traversing the elements in the collection. Usage: Iterator: To use Iterator, you need to first obtain an Iterator object, and then call the MoveNext() method to move to the next

How to use the os module to traverse files in a directory in Python3.x In Python, we can use the os module to operate files and directories. The os module is an important module in the Python standard library, providing many operating system-related functions. In this article, we will explain how to use the os module to iterate through all files in a directory. First, we need to import the os module: importos Next, we can use the os.walk() function to walk the directory.
