Home Web Front-end JS Tutorial 提高jQuery性能优化的技巧

提高jQuery性能优化的技巧

May 16, 2016 pm 03:47 PM
jquery Performance optimization

这篇文章主要深入介绍了提高jQuery性能优化的技巧,有需要的小伙可以来参考下。

下面把提高jQuery性能优化技巧给大家分享如下:

缓存变量

DOM遍历是昂贵的,所以尽量将会重用的元素缓存。

// 糟糕
h = $('#element').height();
$('#element').css('height',h-20);
// 建议
$element = $('#element');
h = $element.height();
$element.css('height',h-20);
Copy after login

避免全局变量

jQuery与javascript一样,一般来说,最好确保你的变量在函数作用域内。

// 糟糕
$element = $('#element');
h = $element.height();
$element.css('height',h-20);
// 建议
var $element = $('#element');
var h = $element.height();
$element.css('height',h-20);
Copy after login

使用匈牙利命名法

在变量前加$前缀,便于识别出jQuery对象。

// 糟糕
var first = $('#first');
var second = $('#second');
var value = $first.val();
// 建议 - 在jQuery对象前加$前缀
var $first = $('#first');
var $second = $('#second'),
var value = $first.val();
Copy after login

使用 Var 链(单 Var 模式)

将多条var语句合并为一条语句,我建议将未赋值的变量放到后面。

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

请使用'On'

在新版jQuery中,更短的 on(“click”) 用来取代类似 click() 这样的函数。在之前的版本中 on() 就是 bind()。自从jQuery 1.7版本后,on() 附加事件处理程序的首选方法。然而,出于一致性考虑,你可以简单的全部使用 on()方法。

// 糟糕
$first.click(function(){
    $first.css('border','1px solid red');
    $first.css('color','blue');
});
$first.hover(function(){
    $first.css('border','1px solid red');
})
// 建议
$first.on('click',function(){
    $first.css('border','1px solid red');
    $first.css('color','blue');
})
$first.on('hover',function(){
    $first.css('border','1px solid red');
})
Copy after login

精简javascript

一般来说,最好尽可能合并函数。

// 糟糕
$first.click(function(){
    $first.css('border','1px solid red');
    $first.css('color','blue');
});
// 建议
$first.on('click',function(){
    $first.css({
        'border':'1px solid red',
        'color':'blue'
    });
});
Copy after login

链式操作

jQuery实现方法的链式操作是非常容易的。下面利用这一点。

// 糟糕
$second.html(value);
$second.on('click',function(){
    alert('hello everybody');
});
$second.fadeIn('slow');
$second.animate({height:'120px'},500);
// 建议
$second.html(value);
$second.on('click',function(){
    alert('hello everybody');
}).fadeIn('slow').animate({height:'120px'},500);
Copy after login

维持代码的可读性

伴随着精简代码和使用链式的同时,可能带来代码的难以阅读。添加缩紧和换行能起到很好的效果。

// 糟糕
$second.html(value);
$second.on('click',function(){
    alert('hello everybody');
}).fadeIn('slow').animate({height:'120px'},500);
// 建议
$second.html(value);
$second
    .on('click',function(){ alert('hello everybody');})
    .fadeIn('slow')
    .animate({height:'120px'},500);
Copy after login

选择短路求值

短路求值是一个从左到右求值的表达式,用 &&(逻辑与)或 || (逻辑或)操作符。

// 糟糕
function initVar($myVar) {
    if(!$myVar) {
        $myVar = $('#selector');
    }
}
// 建议
function initVar($myVar) {
    $myVar = $myVar || $('#selector');
}
Copy after login

选择捷径

精简代码的其中一种方式是利用编码捷径。

// 糟糕
if(collection.length > 0){..}
// 建议
if(collection.length){..}
Copy after login

繁重的操作中分离元素

如果你打算对DOM元素做大量操作(连续设置多个属性或css样式),建议首先分离元素然后在添加。

// 糟糕
var 
    $container = $("#container"),
    $containerLi = $("#container li"),
    $element = null;
$element = $containerLi.first(); 
//... 许多复杂的操作
// better
var 
    $container = $("#container"),
    $containerLi = $container.find("li"),
    $element = null;
$element = $containerLi.first().detach(); 
//... 许多复杂的操作
$container.append($element);
Copy after login

熟记技巧

你可能对使用jQuery中的方法缺少经验,一定要查看的文档,可能会有一个更好或更快的方法来使用它。

// 糟糕
$('#id').data(key,value);
// 建议 (高效)
$.data('#id',key,value);
Copy after login

使用子查询缓存的父元素

正如前面所提到的,DOM遍历是一项昂贵的操作。典型做法是缓存父元素并在选择子元素时重用这些缓存元素。

// 糟糕
var 
    $container = $('#container'),
    $containerLi = $('#container li'),
    $containerLiSpan = $('#container li span');
// 建议 (高效)
var 
    $container = $('#container '),
    $containerLi = $container.find('li'),
    $containerLiSpan= $containerLi.find('span');
Copy after login

避免通用选择符

将通用选择符放到后代选择符中,性能非常糟糕。

// 糟糕
$('.container > *'); 
// 建议
$('.container').children();
Copy after login

避免隐式通用选择符

通用选择符有时是隐式的,不容易发现。

// 糟糕
$('.someclass :radio'); 
// 建议
$('.someclass input:radio');
Copy after login

优化选择符

例如,Id选择符应该是唯一的,所以没有必要添加额外的选择符。

// 糟糕
$('p#myid'); 
$('p#footer a.myLink');
// 建议
$('#myid');
$('#footer .myLink');
Copy after login

避免多个ID选择符在此强调,ID 选择符应该是唯一的,不需要添加额外的选择符,更不需要多个后代ID选择符。

// 糟糕
$('#outer #inner'); 
// 建议
$('#inner');
Copy after login
Copy after login

坚持最新版本

新版本通常更好:更轻量级,更高效。显然,你需要考虑你要支持的代码的兼容性。例如,2.0版本不支持ie 6/7/8。摒弃弃用方法关注每个新版本的废弃方法是非常重要的并尽量避免使用这些方法。

// 糟糕
$('#outer #inner'); 
// 建议
$('#inner');
Copy after login
Copy after login

利用CDN

谷歌的CND能保证选择离用户最近的缓存并迅速响应。(使用谷歌CND请自行搜索地址,此处地址以不能使用,推荐jquery官网提供的CDN)。

必要时组合jQuery和javascript原生代码

如上所述,jQuery就是javascript,这意味着用jQuery能做的事情,同样可以用原生代码来做。原生代码(或vanilla)的可读性和可维护性可能不如jQuery,而且代码更长。但也意味着更高效(通常更接近底层代码可读性越差,性能越高,例如:汇编,当然需要更强大的人才可以)。牢记没有任何框架能比原生代码更小,更轻,更高效(注:测试链接已失效,可上网搜索测试代码)。鉴于vanilla 和 jQuery之间的性能差异,我强烈建议吸收两人的精华,使用(可能的话)和jQuery等价的原生代码。

最后忠告
最后,我记录这篇文章的目的是提高jQuery的性能和其他一些好的建议。如果你想深入的研究对这个话题你会发现很多乐趣。记住,jQuery并非不可或缺,仅是一种选择。思考为什么要使用它。DOM操作?ajax?模版?css动画?还是选择符引擎?或许javascript微型框架或jQuery的定制版是更好的选择。

以上就是本文针对提高jQuery性能优化详细介绍,希望对大家有所帮助,更多相关教程请访问jQuery视频教程

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)

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.

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

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