Suggestions for writing better jquery code
2013/12/05 | Category: Web front end, development | 15 Reviews | Tags: JQUERY
Share to: theThis article by Bole Online-yanhaijing translation from Mathew Carella. Welcome to the technical translation team. Please refer to the requirements at the end of this article for reprint.
Articles that discuss the performance of jquery and JavaScript are not uncommon. However, I plan to summarize some of the speed techniques and some of my own suggestions to improve your jquery and JavaScript code. Good code can lead to speed improvements. Fast rendering and responsiveness means a better user experience.
First, keep in mind that jquery is JavaScript. This means that we should take the same coding conventions, style guides and best practices.
First, if you're a novice JavaScript, I suggest you read the best practices for JavaScript beginners, a high-quality JavaScript tutorial that you'd better read before you touch 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 the elements that will be reused.
12345678910 |
// 糟糕 h = $( ‘#element‘ ).height(); $( ‘#element‘ ).css( ‘height‘ ,h-20); // 建议 $element = $( ‘#element‘ ); h = $element.height(); $element.css( ‘height‘ ,h-20); |
Avoid global variables
jquery, like JavaScript, is generally preferable to ensure that your variables are within the scope of the function.
1234567891011 |
// 糟糕 $element = $( ‘#element‘ ); h = $element.height(); $element.css( ‘height‘ ,h-20); // 建议 var $element = $( ‘#element‘ ); var h = $element.height(); $element.css( ‘height‘ ,h-20); |
Using the Hungarian nomenclature
Prefix the variable with $ to make it easy to identify the jquery object.
1234567891011 |
// 糟糕 var first = $( ‘#first‘ ); var second = $( ‘#second‘ ); var value = $first.val(); // 建议 - 在jQuery对象前加$前缀 var $first = $( ‘#first‘ ); var $second = $( ‘#second‘ ), var value = $first.val(); |
Using the var chain (single var mode)
To combine multiple VAR statements into one statement, I recommend that you put unassigned variables behind.
123456789 |
var $first = $( ‘#first‘ ), $second = $( ‘#second‘ ), value = $first.val(), k = 3, cookiestring = ‘SOMECOOKIESPLEASE‘ , i, j, myArray = {}; |
Please use ' on '
In the new version of jquery, Shorter on ("click") is used to replace functions like Click (). In the previous version, on () is bind (). Since the jquery 1.7 release, ON ()? The preferred method for attaching event handlers. However, for consistency reasons, you can simply use the on () method.
1234567891011121314151617181920 |
// 糟糕
$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‘
);
})
|
Thin JavaScript
In general, it is best to combine functions as much as possible.
123456789101112131415 |
// 糟糕 $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‘ }); }); |
Chained operation
The chained operation of the jquery implementation method is very easy. Use this point below.
123456789101112131415 |
// 糟糕 $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); |
Maintain the readability of your code
The
is accompanied by thin code and the use of chaining, which can lead to hard-to-read code. Adding a shrink and line break can be a good result.
1234567891011121314 |
// 糟糕 $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); |
Select short-Circuit evaluation
A short-circuit evaluation is an expression that evaluates from left to right, with && (logical AND) or | | (logical OR) operators.
12345678910111213 |
// 糟糕 function initVar($myVar) { if (!$myVar) { $myVar = $( ‘#selector‘ ); } } // 建议 function initVar($myVar) { $myVar = $myVar || $( ‘#selector‘ ); } |
Choose a shortcut
One way to streamline your code is to take advantage of coding shortcuts.
1234567 |
// 糟糕 if (collection.length > 0){..} // 建议 if (collection.length){..} |
Separation of elements in heavy operations
If you are going to do a lot of work on DOM elements (setting multiple properties or CSS styles consecutively), it is recommended that you first detach the elements and then add them.
123456789101112131415161718192021 |
//Bad 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); |
Memorizing skills
You may have a lack of experience with the methods in jquery, be sure to review the documentation, and there may be a better or faster way to use it.
1234567 |
// 糟糕 $( ‘#id‘ ).data(key,value); // 建议 (高效) $.data( ‘#id‘ ,key,value); |
Using the parent element of a subquery cache
As mentioned earlier, Dom traversal is an expensive operation. A typical practice is to cache the parent element and reuse those cached elements when the child element is selected.
12345678910111213 |
// 糟糕 var $container = $( ‘#container‘ ), $containerLi = $( ‘#container li‘ ), $containerLiSpan = $( ‘#container li span‘ ); // 建议 (高效) var $container = $( ‘#container ‘ ), $containerLi = $container.find( ‘li‘ ), $containerLiSpan= $containerLi.find( ‘span‘ ); |
Avoid Universal selectors
It is very bad to put a generic selector in a descendant selector.
1234567 |
// 糟糕 $( ‘.container > *‘ ); // 建议 $( ‘.container‘ ).children(); |
Avoid implicit universal selectors
Universal selectors are sometimes implicit and not easily discoverable.
1234567 |
// 糟糕 $( ‘.someclass :radio‘ ); // 建议 $( ‘.someclass input:radio‘ ); |
Refine selectors
For example, the ID selector should be unique, so there is no need to add additional selectors.
12345678 |
// 糟糕 $( ‘div#myid‘ ); $( ‘div#footer a.myLink‘ ); // 建议 $( ‘#myid‘ ); $( ‘#footer .myLink‘ ); |
Avoid multiple ID selectors
In this emphasis, the ID selector should be unique, no additional selectors need to be added, and multiple descendant ID selectors are not required.
1234567 |
// 糟糕 $( ‘#outer #inner‘ ); // 建议 $( ‘#inner‘ ); |
Stick to the latest version
The new version is usually better: more lightweight and more efficient. Obviously, you need to consider the compatibility of the code you want to support. For example, the 2.0 version does not support IE 6/7/8.
Discard deprecated methods
It is important to focus on each new version of the deprecated method and avoid using these methods as much as possible.
1234567891011 |
// 糟糕 - live 已经废弃 $( ‘#stuff‘ ).live( ‘click‘ , function () { console.log( ‘hooray‘ ); }); // 建议 $( ‘#stuff‘ ).on( ‘click‘ , function () { console.log( ‘hooray‘ ); }); // 注:此处可能不当,应为live能实现实时绑定,delegate或许更合适 |
Leveraging CDN
Google's CND ensures that the most recent cache is selected from the user and responds quickly. (Use Google CND, please search the address, where the address can not be used, recommended by the jquery website CDN).
Combine jquery and JavaScript native code if necessary
As mentioned above, jquery is JavaScript, which means that what you can do with jquery can also be done using 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 (often closer to lower-level code readability and higher performance, for example: compilation, which of course requires more powerful talent). Keep in mind that no framework can be smaller, lighter, and more efficient than native code (note: The test link is invalid and the test code can be searched online).
Given the performance differences between vanilla and jquery, I strongly recommend absorbing the essence of the two, using the native code equivalent to the jquery (if possible).
Final advice
Finally, the purpose of my 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 indispensable, it's just a choice. Think about why you should use it. Dom operation? Ajax? Templates? CSS animations? or the selector engine? Perhaps a JavaScript mini-frame or a custom version of jquery is a better choice.