Four principles and five tips for writing effective jQuery code

  • 2020-03-30 02:42:32
  • OfStack

Principles of jQuery:

1. Don't overuse jQuery

1. No matter how fast jQuery is, it cannot be compared with the native javascript methods, and the jQuery objects created contain a large amount of information. So where native methods are available, try to avoid jQuery.


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


2. Many jQuery methods have two versions, one for jQuery objects and one for jQuery functions. Since the latter does not operate through jQuery objects, it is relatively inexpensive and fast.


var $text = $("#text");
var $ts = $text.text();
//Modified left
var $text = $("#text");
var $ts = $.text($text);

Here is the built-in function that USES "$.text()", and other similar functions such as "$.data()".


2. Cache jQuery objects

Finding DOM elements is actually quite a bit of memory overhead, so use the selector as few times as possible, and cache the selected results as much as possible for future reuse. Remember, never let the same selector appear multiple times.

Such as:


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

3. Less DOM structure changes

If you want to change the DOM structure many times, take out the part you want to change first and put it back after the change is done. The basic idea here is to create in memory what you really want and then do the most efficient DOM update operation possible.

Such as:


var top_100_list = [...], //Here's an array of 100 strings & PI;
$mylist = $("#mylist"); 
for (var i=0, l=top_100_list.length; i<l; i++){
    $mylist.append("<li>" + top_100_list[i] + "</li>"); //100 DOM operations
}
 Modified left 
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<l; i++){
    top_100_li += "<li>" + top_100_list[i] + "</li>";
} 
$mylist.html(top_100_li);//DOM manipulation only happens once

Four, naming norms

JQuery code inevitably contains JS code. How to make jQuery code look rigorous and orderly and standardize their own naming rules can better improve the reading of the code.

Function getResultByUserId(){.. }, follow the camel nomenclature, lowercase, capitalized, as short as possible and clear meaning of the method.

It can also be defined as:


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

Function method(recordIdx, recordVal){.. }, the same as the name of the function, the parameters of the use of abbreviations.
Name is to make sense, some of the attributes of the abbreviation is also very elegant, such as: index: idx; Value: val. Length: len; Name: nm; , etc...

3. Variable name: var user_id; Var user_list_tab; Var user_list_tr_1; Generally, the word segmentation is underlined, according to the "named _ element _ index" rule.

The variable names of jQuery objects are prefixed with "$" to distinguish javascript objects.


JQuery writing tips:

One, the selector chooses the best

Selectors are the foundation of jQuery, how to choose the most efficient selectors, first to understand the performance differences of various selectors.

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

JQuery automatically calls the browser's native methods (getElementById()) internally. The getElementByTagName ()) , so it's fast.

Class selector: $(".class ");

JQuery traverses all DOM nodes looking for class= class DOM objects, so the execution is slow.

(3) pseudo-class selector and attribute selector: $(":Type"); = 'Value' $(" [Attribute] ");

Because the browser has no native methods for them, these selectors are the slowest to execute. However, it is not ruled out that some third-party browsers add querySelector() and querySelectorAll() methods, thus making such selectors significantly more powerful.

Two, chain writing method

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

With chaining, jQuery automatically caches the results of each step, faster than with non-chaining (manual caching).


3. Efficient circulation

Looping is always a time-consuming operation, and javascript native looping methods for and while are faster than jQuery's ".each()." And for the for loop, this is the most efficient way to write it.


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

It is much more efficient to declare a variable and then loop through it than to iterate through the array "for (var I in arr)", and to loop through the array length "for (var I = 0; I < Arr. Length; I++) "high efficiency!

Four, string concatenation

Concatenation of strings is often encountered in development. It is very inefficient to concatenate strings by "+=". We can use the ".join() "method of arrays.


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 native method of ".push() "for arrays, but it's actually a little faster to just use arr[I] or arr[arr.length], but it's not that different.

Five, page load

Although the $(function () {}); It's really useful, it's done after all the DOM elements are loaded. If you find that your page is always in load state, this function is probably responsible. You can reduce the CPU usage when the page loads by binding the jQuery function to the $(window).load event.


$(window).load(function(){
    //JQuery functions that are initialized after the page is fully loaded (including all the DOM elements and JS code).
});

Some special effects features, such as drag and drop, visual effects and animation, preloading hidden images, etc., are suitable for this technique.


Related articles: