How to write efficient jQuery code

JQuery writing principles of:


 

First, do not over-use jQuery

  1. jQuery go even faster, it can not be compared with the native javascript method, and the amount of information contained in the jQuery object the establishment of very large. So there are occasions native methods you can use, try to avoid using jQuery.

  E.g:

$("a").click(function(){
    alert($(this).attr("id"));
});

  After improvement ↓

$("a").click(function(){
    alert(this.id);
});

   2. Many jQuery method has two versions, one version is for use of the jQuery object, another version of jQuery function is available for use. Since the latter does not pass through jQuery object operation, the overhead is relatively small, faster.

  E.g:

var $text = $("#text");
var $ts = $text.text();

  After improvement ↓

var $text = $("#text");
var $ts = $.text($text);

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

 

Second, the jQuery object cache

  Find a DOM element is actually not a small memory overhead, the frequency of use selector should be as little as possible, and cache the selected result as possible, to facilitate later repeated use. Remember, never let the same selectors appear more than once.

   E.g:

$("#top").find("p.classA");
$("#top").find("p.classB");

  After improvement ↓

var cached = $("#top");
cached.find("p.classA");
cached.find("p.classB");

 

Third, small changes DOM structure

  If you want to repeatedly change the DOM structure, we want to change the first part of the first taken out, put it back after the completion of the changes. The basic idea here is to establish what you really want in memory, do one of the most effective last updated DOM manipulation.

  E.g:

var top_100_list = [...], // this is a string array 100   
$ 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 improvement ↓

var top_100_list = [...], 
$ mylist = $ ( "# mylist" ), 
top_100_li = ""; // this variable is used to store strings change 
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); // the DOM operation only once so

 

Fourth, the naming convention

  jQuery code can not help but have mixed JS code, how to make reading of the jQuery code look strict, orderly, regulate their own naming conventions to better improve the code.

  1. function name: function getResultByUserId () {..}, follow camel nomenclature, lowercase first letter of the word capitalized, as short as possible and clearly expressed intention methods.

  Also can be defined as:

$.flushCartItemList = function() {
    isAjaxDate = true;
}

 

  2. Parameter name: function methodNm ( recordIdx , recordVal ) {..}, with function names, abbreviations parameters as possible.

Naming is to be meaningful, some abbreviations property is also very particular about, for example: index: idx; value: val; length: len; Name: nm; and so on ...

  

  3. Variable names such as: var $ hidd_userId; var $ tbl_userList ; var $ tr_userList_1 ;, usually underlined word segmentation, according to [ type of element _ name _ index ] rules.

jQuery object to the variable name with " $ prefix" to distinguish javascript object, of course, if the variable is not stored in the object, do not add the prefix.

jQuery writing skills:


 

A selector preferred

  The selector is the basis of jQuery, how to choose the most efficient selectors, first understand the performance differences of various selectors. (The following are listed by descending efficiency)

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

Internal jQuery will automatically invoke the browser's native method ( getElementById () ;, getElementByTagName () ; ), so fast execution speed.

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

jQuery will look through all the DOM node class = Class DOM object, so the slow speed of execution.

  ③ pseudo class selectors and attribute selectors: $ ( ": the Type"); $ ( "[the Attribute = 'the Value']");

Because the browser does not have for their native method, the two selectors execution speed is the slowest. However, some third-party browser does not rule out an increase querySelector () and querySelectorAll () method, so performance will make this type of selector has greatly improved.

 

Second, the wording of the chain

  $("div").find("h3").eq(2).html("Hello");

When using a chain wording, jQuery will automatically cache the results of each step, faster than unchained writing (manually cache).

 

Third, efficient recycling

  Circulation is always a time-consuming operation, JavaScript native methods for recycling and while, than jQuery's " .each () " fast. Moreover, this most efficient on the following wording for loop.

for (var i = 0, len = array.length; i < len; i++) {
  // alert(i);
}

First declare a variable, then loop operation efficiency than through the array " much higher than the cycle length of the array also made" high "efficiency!for (var in arr)”for (var i = 0; i < arr.length; i++)

 

Fourth, string concatenation

  String concatenation often encountered in the development, use "+ =" approach to string concatenation efficiency is very low, we can use the "array .join () " method.

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 method native array. " The Push () ", in fact, the direct use arr [i] or arr [arr.length] way to be a little faster, but the difference is not great.

 

Fifth, the page loads

  Although $ (function () {}); really useful, it is done in all loading DOM elements. If you find that your page has been loaded in the state, most likely due to this function. You can jQuery function by binding to the methods $ (window) .load event to reduce cpu usage when the page is loaded.

$ (window) .load ( function () {
     // page is fully loaded ( including all elements and JS code DOM ) jQuery function after initialization. 
});

Since "$ (function {});" and "$ (window) .load (function () {});" triggering time is not the same, the latter is triggered at the latest, so that some special effects features, such as drag and drop, visual effects and animation, pre-loaded hidden images, etc., can take advantage of this.

Reproduced in: https: //www.cnblogs.com/lishaofei/p/3616557.html

Guess you like

Origin blog.csdn.net/weixin_33692284/article/details/94490603