Home  >  Article  >  Web Front-end  >  4 principles and 5 tips for writing efficient jQuery code_jquery

4 principles and 5 tips for writing efficient jQuery code_jquery

WBOY
WBOYOriginal
2016-05-16 16:51:19943browse

jQuery writing principles:

1. Don’t overuse jQuery

1. No matter how fast jQuery is, it cannot be compared with the native javascript method, and the jQuery object created contains a huge amount of information. Therefore, when there are native methods that can be used, try to avoid using jQuery.

Copy code The code is as follows:

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


2. Many jQuery methods have two versions, one for jQuery objects and the other for jQuery functions. Since the latter does not operate through jQuery objects, it has relatively less overhead and is faster.

Copy code The code is as follows:

var $text = $("#text");
var $ts = $text.text();
//Improved↓
var $text = $("#text");
var $ts = $.text($text );

Here is the built-in function of "$.text()", and other similar ones include "$.data()", etc.


2. Caching jQuery objects

Looking for DOM elements actually involves a lot of memory overhead. You should use the selector as few times as possible, and cache the selected results as much as possible to facilitate repeated use in the future. Remember, never have the same selector appear more than once.

For example:

Copy code The code is as follows:

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

3. Make less changes to the DOM structure

If you want to change the DOM structure multiple times, take out the part to be changed first, and then put it back after the changes are completed. The basic idea here is to build what you really want in memory and then do the most efficient update DOM operation at the end.

For example:

Copy code The code is as follows:

var top_100_list = [... ], // Here is an 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
    }
    After 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 top_100_li = "
  • " top_100_list[i] "
  • ";
    }
    $mylist.html(top_100_li);// There is only one DOM operation

    4. Naming conventions

    jQuery code is inevitably mixed with JS code. How to make the jQuery code look rigorous and orderly and standardize your own naming rules can better improve the code. Readability.

    1. Function name: function getResultByUserId(){..}, follow the camel naming method, with the first letter in lowercase and the first letter of the word in uppercase. Try to be as short as possible and clearly express the purpose of the method.

    can also be defined like this:

    Copy code The code is as follows:

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

    2. Parameter name: function method(recordIdx, recordVal){..}, the same as the function name, try to use abbreviations for parameters.
    Names must be meaningful, and the abbreviations of some attributes are also very particular, such as: index: idx; value: val; length: len; name: nm; etc...

    3. Variable names: var user_id; var user_list_tab; var user_list_tr_1;, generally separated by underscores as words, according to the rules of "naming_element_index".

    The variable name of the jQuery object should be prefixed with "$" to distinguish the javascript object.


    jQuery writing skills:

    1. Selector selection

    Selectors are the foundation of jQuery. How to choose the most efficient selector must first understand the performance differences of various selectors.

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

    jQuery internally automatically calls the browser's native methods (getElementById();, getElementByTagName();), so the execution speed is fast.

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

    jQuery will traverse all DOM nodes to find DOM objects with class=Class, so the execution speed is slow.

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

    Because the browser does not have native methods for them, these two selectors are the slowest in execution. However, it is not ruled out that some third-party browsers have added querySelector() and querySelectorAll() methods, which will greatly improve the performance of this type of selector.

    2. Chain writing

     

    Copy code The code is as follows:
    $("div").find("h3").eq (2).html("Hello");

    When using the chain writing method, jQuery will automatically cache the results of each step, which is faster than the non-chain writing method (manual caching).


    3. Efficient circulation

    Looping is always a time-consuming operation. JavaScript’s native loop methods for and while are faster than jQuery’s “.each()”. And regarding the for loop, the following way of writing is the most efficient.

    Copy code The code is as follows:

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

    Declare the variable first and then perform the loop operation. The efficiency is much higher than traversing the array "for (var i in arr)", and it is also more efficient than looping to obtain the array length "for (var i = 0; i < arr.length ; i )" is highly efficient!

    4. String splicing

    String splicing is often encountered in development. Using the "=" method to splice strings is very inefficient. We can use the ".join()" method of the array.

    Copy code 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 to use the native array method ".push()". In fact, it is faster to use arr[i] or arr[arr.length] directly, but the difference is not big.

    5. Page Loading

    Although $(function(){}); is indeed useful, it is completed after all DOM elements are loaded. If you find that your page is always loading, it is most likely caused by this function. You can reduce CPU usage when the page loads by binding a jQuery function to the $(window).load event.

    Copy code The code is as follows:

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

    Some special effects functions, such as drag and drop, visual effects and animations, preloading hidden images, etc., are suitable for this technology.

    Statement:
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn