A summary of efficient jquery code writing techniques

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.

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.

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

Bad $element = $ (' #element '); h = $element. Height (); $element. css (' height ', h-20);//suggest 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 = $first. val ();//recommendation-add $ prefix to the jquery object var $first = $ (' #fir St '), var $second = $ (' #second '), var = $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 = $ (' #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 (). 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 ');})    Suggested $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 '); /Suggested $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.

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

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 operation $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 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 '),    $containerLi = $ (' #container Li '),    $containerLiSpan = $ (' #container Li span ');//recommended (efficient) 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.

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 ');//Recommended $ (' #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 has discarded $ (' #stuff '). Live (' click ', Function () {  console.log (' Hooray ');}); /Recommended $ (' #stuff '). On (' click ', Function () {  console.log (' Hooray ');}); /Note: This may be inappropriate, real-time binding for live can be delegate, perhaps 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).

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.

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.