4 Principles and 5 tips for writing efficient jquery code _jquery

Source: Internet
Author: User
Tags array length cpu usage

The principles of jquery writing:

First, do not overdo the use of jquery

1. jquery is faster than the native JavaScript method, and the created jquery object contains a huge amount of information. So there are occasions where native methods can be used, as far as possible to avoid using jquery.

Copy Code code as follows:

$ ("a"). Click (function () {
Alert ($ (this). attr ("id"));
});
After the improvement ↓
$ ("a"). Click (function () {
alert (this.id);
});


2. Many jquery methods are available in two versions, one for the jquery object and the other for the jquery function. Because the latter does not operate through the jquery object, the relative overhead is relatively small and faster.

Copy Code code as follows:

var $text = $ ("#text");
var $ts = $text. Text ();
After the improvement ↓
var $text = $ ("#text");
var $ts = $.text ($text);

Here is the "$.text ()" Built-in functions, and other similar "$.data ()" and so on.


Second, caching jquery objects

Looking up a DOM element actually has a very small memory overhead, the fewer times the selector should be used, the better, and caching the selected results as much as possible for later reuse. Remember, never let the same selector appear more than once.

For example:

Copy Code code as follows:

$ ("#top"). Find ("P.classa");
$ ("#top"). Find ("P.CLASSB");
After the improvement ↓
var cached = $ ("#top");
Cached.find ("P.classa");
Cached.find ("P.CLASSB");

Three, less change DOM structure

If you want to change the DOM structure many times, first take out the part to be changed, and then put it back after the change is complete. The basic idea here is to build what you really want in memory, and then do the most effective update DOM operation.

For example:

Copy Code code as follows:

var top_100_list = [...],//This is an array of 100 strings
$mylist = $ ("#mylist");
For (Var i=0, l=top_100_list.length i<l; i++) {
$mylist. Append ("<li>" + top_100_list[i] + "</li>"); 100 Times DOM Operations
}
After the improvement ↓
var top_100_list = [...],
$mylist = $ ("#mylist"),
Top_100_li = ""; This variable is used to store the changed string
For (Var i=0, l=top_100_list.length i<l; i++) {
Top_100_li + + "<li>" + top_100_list[i] + "</li>";
}
$mylist. HTML (top_100_li);//DOM operation only this time

Four, naming norms

jquery code will inevitably be mixed with JS code, how to make jquery code look rigorous and orderly, the specification of their own naming rules to better improve the reading of the code.

1. Function Name: Functions Getresultbyuserid () {.}, follow camel nomenclature, first letter lowercase, capitalize the first letter of the word, as short as possible and express the intent of the method.

You can also define this:

Copy Code code as follows:

$.flushcartitemlist = function () {
Isajaxdate = true;
}

2. Parameter name: Function method (Recordidx, Recordval) {.}, with function name, parameters as far as possible with abbreviations.
The name is to make sense, some attributes of the abbreviation is also very fastidious, for example: index: IDX; value: val; length: len; name: NM;

3. Variable name: var user_id; var User_list_tab; var user_list_tr_1;, generally the following underline for word segmentation, according to the "named _ element _ Index" rule.

The variable name of the jquery object is prefixed with "$" to distinguish the JavaScript object.


jquery Authoring Tips:

First, select the preferred

The selector is the basis of jquery, how to choose the most efficient selector, first to understand the performance differences of various selectors.

①id selector and Tag element selector: $ ("#ID"); $ ("Tag");

jquery will automatically invoke the native method of the browser (getElementById ();, Getelementbytagname ();), so execution is fast.

② class selector: $ (". Class ");

jquery iterates through all the DOM nodes to find Class=class DOM objects, so the execution is slower.

③ Pseudo class selector and property selector: $ (": Type"); $ ("[attribute= ' Value ']");

Because browsers do not have native methods for them, the two selectors perform the slowest. However, some third-party browsers are not excluded from the addition of the Queryselector () and Queryselectorall () methods, which can greatly improve the performance of such selectors.

Second, the chain-type wording

  

Copy Code code as follows:
$ ("div"). Find ("H3"). EQ (2). HTML ("Hello");

When using a chained style, jquery automatically caches the results of each step faster than the non-chained style (manual caching).


Three, efficient cycle

Loops are always a time-consuming operation, and JavaScript native loop methods for and while are faster than JQuery's ". each ()". And for loops, the following are the most efficient.

Copy Code code as follows:

for (var i = 0, len = Array.Length i < len; i++) {
alert (i);
}

Declaring a variable, then looping, is far more efficient than traversing the array "for (var i-in arr)", or getting the array length "for" (var i = 0; i < arr.length; i++).

Four, string concatenation

String stitching in development will often encounter, "+ +" way to string concatenation of the efficiency is very low, we can use the array of ". Join ()" method.

Copy Code code as follows:

var array = [];

for (var i = 0; i < 10000; i++) {
Array[i] = "<input type= ' button ' value= ' a ' >";
}

document.getElementById ("one"). InnerHTML = Array.join ("");

I used to like the primitive way of using arrays ". Push ()", in fact, directly with Arr[i] or arr[arr.length the way to faster, but the difference is not very big.

Five, page load

Although $ (function () {}); is really useful, it is done in all DOM element loading. If you find that your page has been loaded in the state, it is likely that this function caused. You can reduce the CPU usage when the page is loaded by binding the jquery function to the $ (window). Load event method.

Copy Code code as follows:

$ (window). Load (function () {
jquery function initialized after the page has completely loaded (including all the DOM elements and JS code).
});

Some special effects, such as drag and drop, visual effects and animations, preload hidden images and so on, are suitable for this technology.

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.