With JQuery's integration and encapsulation of JS, it makes page operations more arbitrary. Therefore, only by following good specifications can the code be more efficient and robust. Here are some examples of how to operate JQuery efficiently!
JQuery coding principles:
I. Do not over-use jQuery
1. jQuery is faster and cannot be compared with the native javascript method, and the created jQuery object contains a large amount of information. Therefore, when there are scenarios where native methods can be used, avoid using jQuery whenever possible.
The Code is as follows:
$ ("A"). click (function (){
Alert ($ (this). attr ("id "));
});
// Improved renewal
$ ("A"). click (function (){
Alert (this. id );
});
2. Many jQuery methods have two versions, one for jQuery objects and the other for jQuery functions. Because the latter does not operate on jQuery objects, it has relatively low overhead and high speed.
The Code is as follows:
Var $ text = $ ("# text ");
Var $ ts = $ text. text ();
// Improved renewal
Var $ text = $ ("# text ");
Var $ ts = $. text ($ text );
Here we use the built-in functions of "$. text ()", and others are similar to "$. data.
Ii. cache jQuery objects
There is actually a small memory overhead for searching DOM elements. The smaller the number of selectors, the better. In addition, you can cache the selected results as much as possible to facilitate future use. Remember, never let the same selector appear multiple times.
For example:
The Code is as follows:
$ ("# Top"). find ("p. classA ");
$ ("# Top"). find ("p. classB ");
Improved renewal
Var cached = $ ("# top ");
Cached. find ("p. classA ");
Cached. find ("p. classB ");
3. Less DOM Structure Modification
If you want to change the DOM structure multiple times, extract the modified part first, and put it back. The basic idea here is to create what you really want in the memory, and finally perform the most effective DOM update operation.
For example:
The Code is as follows:
Var top_100_list = [...], // here is the array of 100 strings
$ Mylist = $ ("# mylist ");
For (var I = 0, l = top_100_list.length; I $ Mylist. append ("
"+ Top_100_list [I] +""); // 100 DOM operations
}
Improved renewal
Var top_100_list = [...],
$ Mylist = $ ("# mylist "),
Top_100_li = ""; // This variable is used to store changed strings.
For (var I = 0, l = top_100_list.length; I Top_100_li + ="
"+ Top_100_list [I] +"";
}
Export mylist.html (top_100_li); // The DOM operation is performed only once.
Iv. Naming rules
JavaScript code is not included in jQuery code. How to Make jQuery Code look rigorous and orderly and standardize its naming rules can better improve code reading.
1. function Name: function getResultByUserId () {...}. Follow the camel naming method. The first letter is in lowercase and the first letter is in uppercase. It should be as short as possible and clearly express the intention of the method.
It can also be defined as follows:
The Code is as follows:
$. FlushCartItemList = function (){
IsAjaxDate = true;
}
2. Parameter Name: function method (recordIdx, recordVal) {...}, with the same function name. The parameter name should be abbreviated as much as possible.
Naming is meaningful, and the abbreviations of some attributes are also very exquisite, such as: Index: idx; Value: val; Length: len; Name: nm; and so on...
3. variable name: var user_id; var user_list_tab; var user_list_tr_1;. Generally, the following strip is used to separate words and follow the rule "name_element _ Index.
The variable name of the jQuery object must be prefixed with "$" to distinguish javascript objects.
JQuery writing skills:
1. Select the preferred Selector
Selector is the foundation of jQuery. to select the most efficient selector, you must first understand the performance differences of various selectors.
① ID selector and Tag Element selector: $ ("# ID"); $ ("Tag ");
JQuery automatically calls the browser's native method (getElementById ();, getElementByTagName ();), so the execution speed is fast.
② Class selector: $ (". Class ");
JQuery traverses all DOM nodes to find DOM objects of class = Class, so the execution speed is slow.
③ Pseudo-class selector and Attribute selector: $ (": Type"); $ ("[Attribute = 'value']");
Because Browsers Do not have native methods for them, the two Selector Processes the slowest speed. However, it is not ruled out that some third-party browsers have added the querySelector () and querySelectorAll () methods, which greatly improves the performance of such selectors.
Ii. Chain writing
The Code is as follows:
$ ("P"). find ("h3" ).eq(2).html ("Hello ");
When Using Chained writing, jQuery automatically caches the results of each step, which is faster than non-chained writing (manual caching.
Iii. Efficient Circulation
Loop is always a time-consuming operation. The javascript native loop methods for and while are faster than jQuery's ". each. And the for loop is the most efficient.
The Code is as follows:
For (var I = 0, len = array. length; I <len; I ++ ){
// Alert (I );
}
Declaring variables first and then performing loop operations are much more efficient than traversing the array "for (var I in arr)", or getting the array length "for (var I = 0; I <arr. length; I ++) "is efficient!
Iv. String concatenation
String concatenation is often encountered during development. The efficiency of concatenating strings in the "+ =" mode is very low. We can use the ". join ()" method of arrays.
The Code is as follows:
Var array = [];
For (var I = 0; I <10000; I ++ ){
Array [I] ="";
}
Document. getElementById ("one"). innerHTML = array. join ("");
I used to like the NATIVE METHOD OF array ". push () ". In fact, arr [I] Or arr [arr. length] is faster, but the difference is not great.
5. Page Loading
Although $ (function () {}); is indeed useful, it is completed when all DOM elements are loaded. If you find that your page is always in the loading status, it is likely caused by this function. You can bind the jQuery function to the $ (window). load event to reduce the cpu usage during page loading.
The Code is as follows:
$ (Window). load (function (){
// The jQuery function initialized only after the page is fully loaded (including all DOM elements and JS Code.
});
Some special effects, such as drag-and-drop, visual effects and animations, and pre-loading hidden images, are suitable for this technology.