It is not uncommon to discuss jQuery and javascript performance. However, I plan to summarize some speed tips and some of my own suggestions in this article to improve your jQuery and javascript code. Good code will increase the speed. Quick rendering and response means better user experience .... SyntaxHighlighter. all () is not uncommon for articles about jQuery and javascript performance. However, I plan to summarize some speed tips and some of my own suggestions in this article to improve your jQuery and javascript code. Good code will increase the speed. Quick rendering and response means a better user experience. First, keep in mind that jQuery is javascript. This means we should adopt the same encoding practices, style guides and best practices. First of all, if you are a beginner in javascript, I suggest you read "Best Practices for beginners of JavaScript". This is a high-quality javascript tutorial. You 'd better read it before getting started with jQuery. When you are about to use jQuery, I strongly recommend that you follow these guidelines: caching variable DOM traversal is expensive, so try to cache elements that will be reused. Copy code // bad h = values ('height', h-20); // recommended $ element =$ ('# element'); h = element.height()$$element.css ('height ', h-20); copy the code to avoid global variables like jQuery and javascript, in general, it is best to make sure that your variables are within the function scope. Copy code // bad $ element =$ ('# element'); h = element.height();$element.css ('height', h-20 ); // We recommend var $ element = $ ('# element'); var h = element.height();$element.css ('height', h-20); copy the code using the Hungarian name method to add $ prefix before the variable, this makes it easy to identify jQuery objects. Copy the code // bad var first =$ ('# first'); var second =$ ('# second'); var value = $ first. val (); // recommended-add $ prefix var $ first =$ ('# first') before the jQuery object; var $ second =$ ('# second '), var value = $ first. val (); copy the code and use the Var chain (single Var mode) To merge multiple var statements into one statement. I suggest putting unassigned variables behind it. Copy the code var $ first =$ ('# first'), $ second =$ ('# second'), value = $ first. val (), k = 3, cookiestring = 'somecookiesplease', I, j, myArray = {}; Use 'on' to copy code in the new jQuery version, shorter on ("click") is used to replace functions such as click. In earlier versions, on () is bind (). Since jQuery 1.7, the preferred method for attaching event handlers to on. However, for consistency, you can simply use the on () method. Copy code // bad $ first. click (function () {export first.css ('border', '1px solid red'); export first.css ('color', 'blue');}); $ first. hover (function () {export first.css ('border', '1px solid red');}) // We recommend $ first. on ('click', function () {export first.css ('border', '1px solid red'); then first.css ('color', 'blue');}) $ first. on ('hover ', function () {export first.css ('border', '1px solid red');}) copy the code to streamline javascript. In general, it is best to merge functions as much as possible. Copy code // bad $ first. click (function () {export first.css ('border', '1px solid red'); export first.css ('color', 'blue');}); // We recommend $ first. on ('click', function () {export first.css ({'border': '1px solid red', 'color': 'blue '});}); it is very easy to copy the code chain operation jQuery implementation method chain operation. This is used below. Copy code // bad response second.html (value); $ second. on ('click', function () {alert ('Hello everybody') ;}); $ second. fadeIn ('low'); $ second. animate ({height: '120px '}, 500); // We recommend using second.html (value); $ second. on ('click', function () {alert ('Hello everybody ');}). fadeIn ('low '). animate ({height: '120px '}, 500); Copying code to maintain code readability is accompanied by streamlining the code and using the chain, which may make the code hard to read. Adding a thumbnail and a line feed can have a good effect. Copy code // bad response second.html (value); $ second. on ('click', function () {alert ('Hello everybody ');}). fadeIn ('low '). animate ({height: '120px '}, 500); // We recommend using second.html (value); $ second. on ('click', function () {alert ('Hello everybody ');}). fadeIn ('low '). animate ({height: '120px '}, 500); copy the code and select short-circuit. Short-circuit is an expression that calculates values from left to right) or | (logical or) operator. Copy code // bad function initVar ($ myVar) {if (! $ MyVar) {$ myVar = $ ('# selector') ;}} // recommended function initVar ($ myVar) {$ myVar = $ myVar | $ ('# selector');} copy the code to select a shortcut. One of the methods to streamline the code is to use the encoding shortcut. Copy code // bad if (collection. length> 0 ){..} // if (collection. length ){..} if you are planning to perform a large number of operations on DOM elements (consecutively setting multiple attributes or css styles), we recommend that you first separate the elements and then add them. Copy the code // 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); you may not have any experience in using methods in jQuery. You must check the document and may have a better or faster way to use it. Copy code // bad $ ('# id '). data (key, value); // recommended (efficient) $. data ('# id', key, value); copy the code to use the parent element cached by the subquery. As mentioned above, DOM traversal is an expensive operation. A typical practice is to cache parent elements and reuse them when selecting child elements. Copy the code // bad var $ container =$ ('# iner'), $ containerLi =$ ('# container li '), $ containerLiSpan = $ ('# container li span'); // recommended (efficient) var $ container = $ ('# container'), $ containerLi = $ container. find ('lil'), $ containerLiSpan = $ containerLi. find ('span '); copy the code to avoid placing the common selector in the descendant selector. The performance is very poor. Copy code // bad $ ('. container> * '); // suggested $ ('. container '). children (); copy the code to avoid implicit generic selector. The common selector is sometimes implicit and not easy to find. Copy code // bad $ ('. someclass: radio '); // suggested $ ('. someclass input: radio '); copy the code optimization selector. For example, the Id selector should be unique, so there is no need to add additional selector. Copy code // bad $ ('div # myid'); $ ('div # footer. mylink'); // recommended $ ('# myid'); $ (' # footer. mylink'); copy the code to avoid multiple ID delimiters. The ID delimiters must be unique and do not need to be added. Copy the code // bad $ ('# outer # inner'); // recommended $ ('# inner'); copy the code to stick to the latest version, which is usually better: lighter, more efficient. Obviously, you need to consider the code compatibility you want to support. For example, version 2.0 does not support ie 6/7/8. It is very important to discard the discard method and follow the discard method of each new version, and avoid using these methods as much as possible. Copy code // bad-live has been discarded $ ('# stuff '). live ('click', function () {console. log ('hooray') ;}); // suggested $ ('# stuff '). on ('click', function () {console. log ('hooray');}); // Note: This may be inappropriate. It should be possible that live can be bound in real time, and delegate may be more appropriate.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.
A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service