search
HomeWeb Front-endJS Tutorial提高jQuery性能优化的技巧

提高jQuery性能优化的技巧

May 16, 2016 pm 03:47 PM
jqueryPerformance optimization

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

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

缓存变量

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

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

避免全局变量

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

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

使用匈牙利命名法

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

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

使用 Var 链(单 Var 模式)

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

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

请使用'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');
})

精简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'
    });
});

链式操作

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);

维持代码的可读性

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

// 糟糕
$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);

选择短路求值

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

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

选择捷径

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

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

繁重的操作中分离元素

如果你打算对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);

熟记技巧

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

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

使用子查询缓存的父元素

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

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

避免通用选择符

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

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

避免隐式通用选择符

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

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

优化选择符

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

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

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

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

坚持最新版本

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

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

利用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
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
Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

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's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

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.

See all articles

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

MantisBT

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.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor