search
HomeWeb Front-endJS Tutorial19 guidelines for writing efficient jquery code_jquery

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 novice, I recommend you read "24 Best Practices for JavaScript Beginners". This is a high-quality JavaScript tutorial. It is best to read it before contacting jQuery.
When you are ready to use jQuery, I strongly recommend that you follow these guidelines:
1. Caching 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);

// Suggestions

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


2 .Avoid Global Variables
With jQuery and 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);

// Suggestions

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


3. Use the Hungarian nomenclature
to prefix the variable with $ to easily identify the jQuery object.
Copy code The code is as follows:

// Oops

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

// 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 similar click() Such a function. In previous versions on() was bind(). Since jQuery version 1.7, on() is the preferred method of 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');
})

// Recommendation
$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');
});

// Suggestions

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


7. Chain operation
It is very easy for jQuery to implement chain operation of methods. 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);

// Suggestions

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


8. Maintain the readability of the code
Along with streamlining the code and using chaining, it may make the code 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);

// Suggestions

$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 && ( Logical AND) or || (Logical OR) operator.
Copy code The code is as follows:

// Oops

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

// Suggestions

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


10. Choose one of the shortcuts
to simplify the code One way is to take advantage of coding shortcuts.
Copy code The code is as follows:

// Oops

if(collection.length > 0){..}

// Suggestions

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

// better

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

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

$container.append($element);


12. Memorize skills
You may lack experience in using methods in jQuery, be sure to check 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);

// Suggestions (efficient)

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


13. Cache parent elements 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');

// Suggestions (efficient)

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


14. Avoid universal selectors
Putting universal selectors into descendant selectors has very poor performance.
Copy code The code is as follows:

// Oops

$('.container > *');

// Suggestions

$('.container').children();
Avoid implicit universal selectors
Universal selectors are sometimes implicit and difficult to find.

// Oops

$('.someclass :radio');

// Suggestions

$('.someclass input:radio');
Optimize selectors
For example, the Id selector should be unique, so there is no need to add additional selectors.

// Oops

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

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


15. Avoid multiple ID selectors
emphasize here , 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');

// Suggestions

$('#inner');


16. Stick to the latest version
Newer 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 IE 6/7/8.

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

// Suggestion
$('#stuff').on('click', function() {
console.log('hooray');
});


// Note: This may be inappropriate. Live can achieve real-time binding, and delegate may be more appropriate
17. Use CDN
Google's CND can ensure 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).

18. 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 not be as readable and maintainable as 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). Remember that no framework can be smaller, lighter, and more efficient than native code

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

19. Final advice
Finally, the purpose of recording this article is to improve 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 customized version of jQuery would be a better choice.

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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

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 Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

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