Write an efficient jquery code

Source: Internet
Author: User
Tags deprecated

Recently wrote a lot of JS, although the effect has been achieved, but always feel that they write JS in the performance can also have a great increase. This article I plan to summarize some of the online and 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. I would like to remind myself of this article.
First, we recommend the jquery API documentation http://www.css88.com/jqapi-1.9/, who will tell you which issues you should be aware of when using jquery, performance recommendations, and which situations may cause problems. To help you better understand and master jquery.
Second, remember that jquery is JavaScript in your head. This means that we should take the same coding conventions, style guides and best practices.
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 '), Code class= "HTML Spaces" >  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 (). The preferred method of on () attaching event handlers since the jquery 1.7 release. 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.

Oops $first. Click (function () {    $first. css (' border ', ' 1px solid red ');    $first. CSS (' Color ', ' Blue ');}); Recommended $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.

Bad $second.html (value); $second. On (' click ', Function () {    alert (' Hello Everybody ');}); $second. FadeIn (' slow '), $second. Animate ({height: ' 120px '},500);//Recommended $second.html (value); $second. On (' click ', function () {    alert (' Hello Everybody ');}). FadeIn (' slow '). Animate ({height: ' 120px '},500);

maintaining the readability of your code can lead to hard-to-read code while simplifying code and using chaining. Adding a shrink and line break can be a good result.

Bad $second. HTML (value); $second. On (' click ', Function () {    alert (' Hello Everybody ')}). FadeIn (' slow '). Animate ({height: ' 120px '},500); It is recommended to $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.

Bad function Initvar ($myVar) {    if (! $myVar) {        $myVar = $ (' #selector ');}    }//Suggested function Initvar ($myVar) {    $myVar = $myVar | | $ (' #selector ');}

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

Bad if (Collection.length > 0) {:}//Suggest 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.

Bad var    $container = $ ("#container"),    $containerLi = $ ("#container li"),    $element = null; $element = $con Tainerli.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.

Poor $ (' #id '). Data (Key,value); Recommended (efficient) $.data (' #id ', key,value);

using the parent element of the 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.

Bad var    $container = $ (' #container '),    $containerLi = $ (' #container Li '),    $containerLiSpan = $ (' # Container Li span '); Recommended (Efficient) var    $container = $ (' #container '),    $containerLi = $container. Find (' Li '),    $containerLiSpan = $ Containerli.find (' span ');

It is very bad to avoid the general selector placing the universal selector in the descendant selector.

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

Avoid implicit universal selectors
Universal selectors are sometimes implicit and not easily discoverable.

Poor $ ('. Someclass:radio '); Suggested $ ('. SomeClass input:radio ');

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

Poor $ (' Div#myid '); $ (' Div#footer a.mylink '); Suggested $ (' #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.

Poor $ (' #outer #inner '); Recommended $ (' #inner ');

It's usually better to stick to the latest version : lighter 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.
It is important to discard deprecated methods that focus on each new version and avoid using them as much as possible.

Bad-Live has been deprecated $ (' #stuff '). Live (' click ', Function () {  console.log (' Hooray ');});//Suggest $ (' #stuff '). On (' click ', function () {  console.log (' Hooray ');}); /Note: This may be inappropriate, real-time binding for live can be delegate, perhaps more appropriate

using 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.
It's all a cliché, but I've found that it's not so good to do it all, and I want to be able to do it all.

Write an efficient jquery code

Related Article

Contact Us

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

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.