A summary of efficient jquery code writing techniques

Source: Internet
Author: User
Tags deprecated

Cache variables

DOM traversal is expensive, so try to cache the elements that will be reused.

// Bad  = $ (' #element '). Height (); $ (' #element '). CSS (' height ', h-20); // Recommended  = $ (' #element '= $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.

// Bad  = $ (' #element '= $element. Height (); $element. css (' height ', h-20); // Recommended 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.

// Bad var first = $ (' #first '); var second = $ (' #second '); var value = $first. val (); // recommendation-Add $ prefix to jquery objects 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.

var  = $ (' #first  '), = $  (' #second '), = $first. Val (),  = 3 ,   = ' Somecookiesplease ',  I,  j,  = {};
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.

//Bad$first. Click (function() {$first. css (' Border ', ' 1px solid red '); $first. CSS (' Color ', ' blue ');}); $first. Hover (function() {$first. css (' Border ', ' 1px solid red ');})//Recommended$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.

// Bad $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);
Maintain the readability of your code

Along with the streamlining of code and the use of chaining, the code can be difficult to read. Adding a shrink and line break can be a good result.

$second. HTML (value); $second. On (' click ',function() {    alert (' Hello Everybody ')}). FadeIn (' slow '). Animate ({height: ' 120px '},500); // Recommended $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) {        = $ (' #selector ');}    } // Recommended function Initvar ($myVar) {    = $myVar | | $ (' #selector ');}
Choose a shortcut

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

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

//Badvar$container= $ ("#container"), $containerLi= $ ("#container Li"), $element=NULL; $element=$containerLi. First ();//... Many complex operations//Bettervar$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.

// Bad $ (' #id '). Data (key,value); // recommended (efficient) $.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.

// Bad var = $ (' #container '),    = $ (' #container Li '),    = $ (' #container li span ');      // recommended (efficient) var = $ (' #container '),    = $container. Find (' Li '),    $containerLiSpan= $      Containerli.find (' span ');
Avoid Universal selectors

It is very bad to put a generic selector in a descendant selector.

// Bad $ ('. Container > * '); // Recommended $ ('. Container '). Children ();
Avoid implicit universal selectors

Universal selectors are sometimes implicit and not easily discoverable.

// Bad $ ('. Someclass:radio '); // Recommended $ ('. SomeClass input:radio ');
Refine selectors

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

// Bad $(' 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.

// Bad $ (' #outer #inner '); // Recommended $ (' #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.

// bad-Live is obsolete $ (function() {  console.log (' Hooray ');}); // Recommended function () {  console.log (' Hooray ');}); // Note: It may be inappropriate here, real-time binding for live can be, delegate may be more appropriate
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).

Reprint Address: http://www.codeceo.com/article/jquery-coding-high-qulity.html

A summary of efficient jquery code writing techniques

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.