Some jQuery coding skills and jQuery coding skills

Source: Internet
Author: User

Some jQuery coding skills and jQuery coding skills

Cache variable

DOM traversal is expensive, so we try to cache elements that will be reused.
// Bad h = fill ('height', h-20); // recommended $ element =$ ('# element'); h = element.height();$element.css ('height', h-20 );

Avoid global variables

JQuery is the same as javascript. In general, it is best to ensure that your variables are within the function scope.
// Bad $ element = $ ('# element'); h = element.height();$element.css ('height', h-20); // suggested var $ element = $ (' # element '); var h = $element.height();$element.css ('height', h-20 );

Using the Hungarian naming method

Add a $ prefix to the variable to identify the jQuery object.
// 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 ();

Use Var chain

Merge multiple var statements into one statement. I suggest placing unassigned variables behind it.
var  $first = $('#first'),  $second = $('#second'),  value = $first.val(),  k = 3,  cookiestring = 'SOMECOOKIESPLEASE',  i,  j,  myArray = {};

Use 'on'

In the new version of jQuery, the 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.
// 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 ');})

Simplified javascript

In general, it is best to merge functions as much as possible.
// 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 '});});

Chain Operation

The chain operation of jQuery implementation method is very easy. This is used below.
// Bad cakes second.html (value); $ second. on ('click', function () {alert ('Hello everybody') ;}); $ second. fadeIn ('low'); $ second. animate ({height: '120px '}, 500); // recommended parameter second.html (value); $ second. on ('click', function () {alert ('Hello everybody ');}). fadeIn ('low '). animate ({height: '120px '}, 500 );

Maintain code readability

While streamlining code and using the chain, it may make the code hard to read. Adding indentation and line breaks can have a good effect.
// Bad cakes second.html (value); $ second. on ('click', function () {alert ('Hello everybody ');}). fadeIn ('low '). animate ({height: '120px '}, 500); // recommended parameter second.html (value); $ second. on ('click', function () {alert ('Hello everybody ');}). fadeIn ('low '). animate ({height: '120px '}, 500 );

Select short-circuit evaluate

Short-circuit evaluate is a left-to-right evaluate expression, using the & (logical and) or | (logical or) operator.
// Bad function initVar ($ myVar) {if (! $ MyVar) {$ myVar = $ ('# selector') ;}} // recommended function initVar ($ myVar) {$ myVar = $ myVar | $ ('# selector ');}

Shortcut Selection

One of the ways to streamline code is to use short-cut encoding.
// Bad if (collection. length> 0) {...} // We recommend if (collection. length ){..}

Separation of elements in heavy operations

If you want 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.
// Bad var $ 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 not have any experience in using jQuery methods. You must check the document. There may be a better or faster way to use it.
// Bad $ ('# id'). data (key, value); // recommended (efficient) $. data (' # id', key, value );

Parent element cached by 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.
// Bad var $ container = $ ('# iner'), $ containerLi = $ ('# container li'), $ containerLiSpan = $ ('# container li span '); // recommended (efficient) var $ container =$ ('# container'), $ containerLi = $ container. find ('lil'), $ containerLiSpan = $ containerLi. find ('span ');

Avoid common Selector

Put the common selector in the descendant selector, and the performance is very bad.
// Bad $ ('. iner> *'); // recommended $ ('. iner'). children ();

Avoid implicit common Selector

The common selector is sometimes implicit and is not easy to find.
// Bad $ ('. someclass: radio'); // suggested $ ('. someclass input: radio ');

Optimized Selection character

For example, the Id selector should be unique, so there is no need to add additional selector.
// Bad $ ('div # myid'); $ ('div # footer. mylink'); // recommended $ ('# myid'); $ (' # footer. mylink ');

Stick to the latest version

The new version is usually better: lighter and 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. Abandon the discard MethodIt is very important to pay attention to the obsolete methods of each new version and try to avoid using these methods.
// 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.

Use CDN

CND ensures that the cache closest to the user is selected and responds quickly. We recommend that you use the CDN provided on the official jquery website. Combine jQuery and javascript native code if necessary
As mentioned above, jQuery is javascript, which means that what jQuery can do can also be done using native code. The readability and maintainability of native code (or vanilla) may be inferior to that of jQuery, and the code is longer. But it also means more efficient (usually closer to the lower-Layer Code, the lower the readability, the higher the performance, for example: Assembly, of course, more powerful talent is needed ). Original article: Workshop

  

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.