Home Web Front-end JS Tutorial 22 suggestions on jquery performance optimization_jquery

22 suggestions on jquery performance optimization_jquery

May 16, 2016 pm 04:46 PM
jquery Performance optimization

First of all, keep in mind that jQuery is javascript. This means we should adopt the same coding conventions, style guides and best practices.

First of all, if you are a javascript newbie, I recommend you read "24 JavaScript Best Practices for Beginners". This is a high-quality javascript tutorial. It is best to read it before getting into jQuery.

When you are ready to use jQuery, I strongly recommend that you follow these guidelines:

1. Cache variables

DOM traversal is expensive, so try to cache reused elements.

Copy code The code is as follows:

//Oops
h=$('# element').height();
$('#element').css('height',h-20);

Copy code The code is as follows:

//Suggestion
$element=$(' #element');
h=$element.height();
$element.css('height',h-20);

2. Avoid global variables

jQuery As with javascript, in general it's best to make sure your variables are within function scope.

Copy code The code is as follows:

//Oops
$element=$(' #element');
h=$element.height();
$element.css('height',h-20);

Copy code The code is as follows:

//Suggestion
var $element=$( '#element');
var h=$element.height();
$element.css('height',h-20);

3. Use Hungarian nomenclature

Add $ prefix before variables to easily identify jQuery objects.

Copy code The code is as follows:

//Oops
var first=$(' #first');
var second=$('#second');
var value=$first.val();

Copy code The code is as follows:

// Suggestion - Prefix the jQuery object with $
var $first=$('#first');
var $second=$('#second'),
var value=$first.val();

4. Use var chain (single var mode)

To combine multiple var statements into one statement, I recommend putting unassigned variables at the end.

Copy code The code is as follows:

var
$first=$('#first '),
$second=$('#second'),
value=$first.val(),
k=3,
cookiestring='SOMECOOKIESPLEASE',
i,
j,
myArray={};

5. Please use 'on'

In the new version of jQuery, the shorter on("click") is used to replace functions like click(). In previous versions on() was bind(). Since jQuery 1.7, on() is the preferred method for attaching event handlers. However, for consistency's sake, you can simply use the on() method all together.

Copy code The code is as follows:

//Oops
$first.click(function (){
$first.css('border','1px solid red');
$first.css('color','blue');
});

$first.hover(function(){
$first.css('border','1px solid red');
})

Copy code The code is as follows:

// Suggestion
$first.on(' click',function(){
$first.css('border','1px solid red');
$first.css('color','blue');
})

$first.on('hover',function(){
$first.css('border','1px solid red');
})

6. Simplify javascript

In general, it’s best to combine functions whenever possible.

Copy code The code is as follows:

//Oops
$first.click(function (){
$first.css('border','1px solid red');
$first.css('color','blue');
});

Copy code The code is as follows:

//Suggestion
$first.on(' click',function(){
$first.css({
'border':'1px solid red',
'color':'blue'
});
}) ;

7. Chain operation

It is very easy to implement method chaining operations in jQuery. Take advantage of this below.

Copy code The code is as follows:

//Oops
$second.html(value );
$second.on('click',function(){
alert('hello everybody');
});
$second.fadeIn('slow');
$second.animate({height:'120px'},500);

Copy code The code is as follows:

//Suggestion
$second.html(value );
$second.on('click',function(){
alert('hello everybody');
}).fadeIn('slow').animate({height:'120px' },500);

8. Maintain code readability

Along with streamlining the code and using chaining, the code may become difficult to read. Adding pinches and line breaks can work wonders.

Copy code The code is as follows:

//Oops
$second.html(value );
$second.on('click',function(){
alert('hello everybody');
}).fadeIn('slow').animate({height:'120px' },500);

Copy code The code is as follows:

//Suggestion
$second.html(value );
$second
.on('click',function(){ alert('hello everybody');})
.fadeIn('slow')
.animate({height: '120px'},500);


9. Select short-circuit evaluation

Short-circuit evaluation is an expression that is evaluated from left to right, using the && (logical AND) or || (logical OR) operators.

Copy code The code is as follows:

//Oops
function initVar($myVar) {
if(!$myVar) {
$myVar=$('#selector');
}
}

Copy code The code is as follows:

//Suggestion
function initVar($myVar) {
$myVar=$myVar || $('#selector');
}

10. Select shortcut

One way to streamline your code is to take advantage of coding shortcuts.

[code]
//Oops
if(collection.length > 0){..}

Copy code The code is as follows:

//Suggestion
if(collection.length) {..}

11. Separate elements during heavy operations

If you plan to do a lot of operations on DOM elements (setting multiple attributes or css styles in succession), it is recommended to detach the elements first and then add them.

Copy code The code is as follows:

//Oops
var
$container=$("#container"),
$containerLi=$("#container li"),
$element=null;

$element=$containerLi.first();
//... Many complex operations

Copy code The code is as follows:

//Suggestion
var
$container =$("#container"),
$containerLi=$container.find("li"),
$element=null;

$element=$containerLi.first().detach();
//... Many complex operations

$container.append($element);

12. Memorize skills

You may be inexperienced with using methods in jQuery, be sure to check out the documentation, there may be a better or faster way to use it.

Copy code The code is as follows:

//Oops
$('#id' ).data(key,value);

Copy code The code is as follows:

// Suggestion (efficient)
$.data ('#id',key,value);

13. Parent elements cached using subqueries

As mentioned earlier, DOM traversal is an expensive operation. A typical approach is to cache parent elements and reuse these cached elements when selecting child elements.

Copy code The code is as follows:

//Oops
var
$container =$('#container'),
$containerLi=$('#container li'),
$containerLiSpan=$('#container li span');

Copy code The code is as follows:

// Suggestion (efficient)
var
$container=$('#container '),
$containerLi=$container.find('li'),
$containerLiSpan= $containerLi.find('span');


14. Avoid universal selectors

Putting the universal selector into a descendant selector has terrible performance.

Copy code The code is as follows:

//Oops
$('.container > ; *');

Copy code The code is as follows:

//Suggestion
$('.container' ).children();

15. Avoid implicit universal selectors

Universal selectors are sometimes implicit and difficult to find.

Copy code The code is as follows:

//Oops
$('.someclass: radio');

Copy code The code is as follows:

//Suggestion
$('.someclass input :radio');

16. Optimization selector

For example, the id selector should be unique, so there is no need to add additional selectors.

Copy code The code is as follows:

//Oops
$('div#myid ');
$('div#footer a.myLink');

Copy code The code is as follows:

// Suggestion
$('#myid' );
$('#footer .myLink');

17. Avoid multiple ID selectors

It is emphasized that the ID selector should be unique, there is no need to add additional selectors, and there is no need for multiple descendant ID selectors.

Copy code The code is as follows:

//Oops
$('#outer # inner');

Copy code The code is as follows:

//Suggestion
$('#inner' );

18. Stick to the latest version

New versions are usually better: more lightweight and more efficient. Obviously, you need to consider the compatibility of the code you want to support. For example, version 2.0 does not support Internet Explorer 6/7/8.

19. Abandon deprecated methods

It is very important to pay attention to deprecated methods with each new version and try to avoid using these methods.

Copy code The code is as follows:

//Oops - live has been abandoned
$( '#stuff').live('click',function() {
console.log('hooray');
});

Copy code The code is as follows:

// Suggestion
$('#stuff' ).on('click',function() {
console.log('hooray');
});
// Note: This may be inappropriate, it should be that live can achieve real-time binding , delegate may be more appropriate

20. Utilize CDN

Google’s CND ensures that the cache closest to the user is selected and responds quickly. (Please search the address yourself when using Google CND. The address here cannot be used. We recommend the CDN provided by jquery official website).

21. Combine jQuery and javascript native code when necessary

As mentioned above, jQuery is javascript, which means that anything you can do with jQuery can also be done with native code. Native code (or vanilla) may be less readable and maintainable than jQuery, and the code is longer. But it also means more efficient (usually the closer to the underlying code the less readable the higher the performance, for example: assembly, which of course requires more powerful people). Keep in mind that no framework can be smaller, lighter, and more efficient than native code (note: the test link is no longer valid, you can search for the test code online).

Given the performance differences between vanilla and jQuery, I highly recommend taking the best of both and using (if possible) native code equivalent to jQuery.

22. Final advice

Finally, I recorded this article with the purpose of improving the performance of jQuery and some other good suggestions. If you want to delve deeper into this topic you will find a lot of fun. Remember, jQuery is not required, just an option. Think about why you want to use it. DOM manipulation? ajax? stencil? css animation? Or a selector engine? Perhaps a javascript microframework or a custom version of jQuery would be a better choice.

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

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

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1253
29
C# Tutorial
1227
24
Performance optimization and horizontal expansion technology of Go framework? Performance optimization and horizontal expansion technology of Go framework? Jun 03, 2024 pm 07:27 PM

In order to improve the performance of Go applications, we can take the following optimization measures: Caching: Use caching to reduce the number of accesses to the underlying storage and improve performance. Concurrency: Use goroutines and channels to execute lengthy tasks in parallel. Memory Management: Manually manage memory (using the unsafe package) to further optimize performance. To scale out an application we can implement the following techniques: Horizontal Scaling (Horizontal Scaling): Deploying application instances on multiple servers or nodes. Load balancing: Use a load balancer to distribute requests to multiple application instances. Data sharding: Distribute large data sets across multiple databases or storage nodes to improve query performance and scalability.

C++ Performance Optimization Guide: Discover the secrets to making your code more efficient C++ Performance Optimization Guide: Discover the secrets to making your code more efficient Jun 01, 2024 pm 05:13 PM

C++ performance optimization involves a variety of techniques, including: 1. Avoiding dynamic allocation; 2. Using compiler optimization flags; 3. Selecting optimized data structures; 4. Application caching; 5. Parallel programming. The optimization practical case shows how to apply these techniques when finding the longest ascending subsequence in an integer array, improving the algorithm efficiency from O(n^2) to O(nlogn).

Nginx Performance Tuning: Optimizing for Speed and Low Latency Nginx Performance Tuning: Optimizing for Speed and Low Latency Apr 05, 2025 am 12:08 AM

Nginx performance tuning can be achieved by adjusting the number of worker processes, connection pool size, enabling Gzip compression and HTTP/2 protocols, and using cache and load balancing. 1. Adjust the number of worker processes and connection pool size: worker_processesauto; events{worker_connections1024;}. 2. Enable Gzip compression and HTTP/2 protocol: http{gzipon;server{listen443sslhttp2;}}. 3. Use cache optimization: http{proxy_cache_path/path/to/cachelevels=1:2k

The Way to Optimization: Exploring the Performance Improvement Journey of Java Framework The Way to Optimization: Exploring the Performance Improvement Journey of Java Framework Jun 01, 2024 pm 07:07 PM

The performance of Java frameworks can be improved by implementing caching mechanisms, parallel processing, database optimization, and reducing memory consumption. Caching mechanism: Reduce the number of database or API requests and improve performance. Parallel processing: Utilize multi-core CPUs to execute tasks simultaneously to improve throughput. Database optimization: optimize queries, use indexes, configure connection pools, and improve database performance. Reduce memory consumption: Use lightweight frameworks, avoid leaks, and use analysis tools to reduce memory consumption.

How to quickly diagnose PHP performance issues How to quickly diagnose PHP performance issues Jun 03, 2024 am 10:56 AM

Effective techniques for quickly diagnosing PHP performance issues include using Xdebug to obtain performance data and then analyzing the Cachegrind output. Use Blackfire to view request traces and generate performance reports. Examine database queries to identify inefficient queries. Analyze memory usage, view memory allocations and peak usage.

Optimizing rocket engine performance using C++ Optimizing rocket engine performance using C++ Jun 01, 2024 pm 04:14 PM

By building mathematical models, conducting simulations and optimizing parameters, C++ can significantly improve rocket engine performance: Build a mathematical model of a rocket engine and describe its behavior. Simulate engine performance and calculate key parameters such as thrust and specific impulse. Identify key parameters and search for optimal values ​​using optimization algorithms such as genetic algorithms. Engine performance is recalculated based on optimized parameters to improve its overall efficiency.

How to use profiling in Java to optimize performance? How to use profiling in Java to optimize performance? Jun 01, 2024 pm 02:08 PM

Profiling in Java is used to determine the time and resource consumption in application execution. Implement profiling using JavaVisualVM: Connect to the JVM to enable profiling, set the sampling interval, run the application, stop profiling, and the analysis results display a tree view of the execution time. Methods to optimize performance include: identifying hotspot reduction methods and calling optimization algorithms

The impact of exception handling on Java framework performance optimization The impact of exception handling on Java framework performance optimization Jun 03, 2024 pm 06:34 PM

Exception handling affects Java framework performance because when an exception occurs, execution is paused and the exception logic is processed. Tips for optimizing exception handling include: caching exception messages using specific exception types using suppressed exceptions to avoid excessive exception handling

See all articles