Home Web Front-end JS Tutorial Tips for writing better jQuery code

Tips for writing better jQuery code

Nov 22, 2016 am 11:49 AM
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 "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:

Cache variables

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

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

Avoid global variables

With jQuery, like JavaScript, in general, it’s best to make sure your variables are within function scope.

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

Use Hungarian nomenclature

Add $ prefix before variables to easily identify jQuery objects.

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

Use Var chain (single Var mode)

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

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

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.

/

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

Streamline javascript

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

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

Chained operations

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

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

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.

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

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.

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

Choose shortcuts

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

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

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 separate the elements first and then add them.

// 糟糕
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

Know the tips

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.

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

Cache parent element using subquery

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.

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

Avoid universal selectors

Putting universal selectors into descendant selectors has terrible performance.

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

Avoid implicit universal selectors

Universal selectors are sometimes implicit and not easy to spot.

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

Optimized selectors

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

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

Avoid multiple ID selectors

I would like to emphasize 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.

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

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.

Discard deprecated methods

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

// 糟糕 - live 已经废弃
$('#stuff').live('click', function() {
 console.log('hooray');
});
// 建议
$('#stuff').on('click', function() {
 console.log('hooray');
});
// 注:此处可能不当,应为live能实现实时绑定,delegate或许更合适
Copy after login

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

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). 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 strongly recommend absorbing the best of both worlds and using (if possible) native code equivalent to 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Detailed explanation of jQuery reference methods: Quick start guide Detailed explanation of jQuery reference methods: Quick start guide Feb 27, 2024 pm 06:45 PM

Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

In-depth analysis: jQuery's advantages and disadvantages In-depth analysis: jQuery's advantages and disadvantages Feb 27, 2024 pm 05:18 PM

jQuery is a fast, small, feature-rich JavaScript library widely used in front-end development. Since its release in 2006, jQuery has become one of the tools of choice for many developers, but in practical applications, it also has some advantages and disadvantages. This article will deeply analyze the advantages and disadvantages of jQuery and illustrate it with specific code examples. Advantages: 1. Concise syntax jQuery's syntax design is concise and clear, which can greatly improve the readability and writing efficiency of the code. for example,

How to remove the height attribute of an element with jQuery? How to remove the height attribute of an element with jQuery? Feb 28, 2024 am 08:39 AM

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

How to tell if a jQuery element has a specific attribute? How to tell if a jQuery element has a specific attribute? Feb 29, 2024 am 09:03 AM

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

Understand the role and application scenarios of eq in jQuery Understand the role and application scenarios of eq in jQuery Feb 28, 2024 pm 01:15 PM

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

See all articles