Why use native JavaScript instead of jQuery?

Source: Internet
Author: User
Tags function definition

With the development of JavaScript itself, more and more people are beginning to prefer to use native javascript instead of various libraries, many of whom emit the voice of native JavaScript instead of JQuery. It's not a bad thing, but it's not necessarily a good thing. If you really want to remove jQuery from the front-end dependency library, I suggest you consider it carefully.

First, JQuery is a third-party library. One of the value of the library's existence is its ability to greatly simplify development. In general, third-party libraries are implemented by native language features and the underlying API library. Therefore, theoretically, any library third-party library can be replaced with native language features, the question is whether it is worthwhile?

The role of JQuery

Quote a jQuery website:

JQuery is a fast, small, and Feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation , and Ajax much simpler with an easy-to-use API that works across a multitude of browsers.

This passage is a modest introduction to JQuery's contribution to the handling of DOM and cross-browser. In fact, this is the main reason why we choose JQuery, and incidentally use some of the tools it brings, such as array tools, Deferred, etc.

For me, the most common features include

    • Querying in the DOM tree
    • Modify DOM tree and DOM related operations
    • Event handling
    • Ajax
    • Deferred and Promise
    • Object and Array processing
    • There is one that has been used but is hard to think of when listing--cross-browser
Who in the hell is replacing who?

All of the features mentioned above can be implemented using native code. In essence, jquery is used instead of native implementations to reduce code and enhance readability-so does jquery replace native code, or does it replace jquery with native code? Can this causal relationship be understood?

I see that in querySelectorAll() lieu $() of the time, can not help thinking, with jQuery a character to solve, why write 16 characters? Most browsers are implemented $() , but do you consider browser compatibility when writing native code $() ? JQuery has been considered!

When I saw a lot of native JavaScript code that created the DOM structure, I couldn't help thinking that jQuery only needed a method chain to solve it, and I could even use code similar to HTML structure (including indentation), such as

// 创建一个 ul 列表并加在 #container 中$("<ul>").append(    $("<li>").append(        $("<a>").attr("href", "#").text("first")),    $("<li>").append(        $("<a>").attr("href", "#").text("second")),    $("<li>").append(        $("<a>").attr("href", "#").text("third"))).appendTo($("#container"));

This code can be document.createElement() implemented completely without problems, except that the amount of code is much larger and there is a lot of repetitive (or similar) code. Of course, these repetitive code can be extracted to write functions ... But JQuery has already done it.

Note, the method of spelling HTML is really weak, both error-prone and difficult to read. If you have a ES6 string template, it's a good idea to use it to write HTML.

In the case of DOM operations, JQuery is still a very useful tool. This is jQuery instead of native JavaScript, as it used to be, and still is.

The Declining JQuery tool function

When JQuery was invented in 2006, there was no ES5 (released in June 2011). Not all browsers are supported even after ES5 is released for a long time. So in this period, in addition to DOM operations, the great contribution of jQuery is to solve cross-browser problems, as well as provide convenient objects and arrays of operational tools, such as each() , index() and and filter so on.

Now ECMAScript has just released a 2017 standard, the browser standard confusion has been a very good solution, the front-end sector has also appeared Babel such translation tools and TypeScript and other new languages. So now we are all at ease to use a variety of new language features, even if the relevant standards of ECMAScript is still in development. In this period, JQuery has provided a large number of tools and methods that have been replaced by the original-the use of a small difference in the case, do prefer to use the native implementation.

In fact, JQuery is also using the native implementation as much as possible to improve execution efficiency. jquery does not abandon these existing native implementations of the tool functions/methods, mainly because of backward compatibility, as well as the same as always provide browser-compatible-after all, not every developer using JQuery will use the translation tool.

So, for JavaScript developers, JQuery does have a number of tools that can be overridden by native JavaScript functions/methods. Like what

    • $.parseJSON()Can be JSON.parse() replaced, but JSON.stringify() also make up for the $.toJSON() lack of jQuery;
    • $.extend()Can be replaced by a partial function of the Object.assign() '
    • $.fnSome methods of data processing tools, such as each() , and index() so can be used Array.prototype in the corresponding tool methods, such as forEach() , and indexOf() so on.
    • $.Deferred()And JQuery Promise can be substituted with native Promise in some cases. They are a good Promise to achieve without ES6.
    • ......

$.fnThat is jQuery.prototype , the prototype of the JQuery object. So the method defined on it is the method of the JQuery object.

These tool methods have been gradually replenished in native JavaScript, but they are still only available in some cases ... Because the jquery object is a unique data structure, the tool methods created for jquery itself have some specific implementations for jquery objects-since DOM operations still cannot throw jquery away, then these methods cannot be completely replaced.

The combination of jQuery and native JavaScript

Sometimes you need to use jQuery, sometimes you don't need it, how do you tell?

The advantage of JQuery is its DOM processing, Ajax, and cross-browser. If you introduce jQuery into your project, it's mostly because of the need for these features. For non-manipulation of the DOM, there is no need to consider the parts of cross-browser (e.g. for translation tools), consider using native JavaScript as much as possible.

So, there's always the intersection of JQuery and native JavaScript, so you have to talk about where you need to be aware.

JQuery objects implement a pseudo-array of partial array functionality

The first thing to note is that the JQuery object is a pseudo-array, which encapsulates a primitive array or pseudo-array (such as a list of DOM nodes).

If you want to get an element, you can use an [] operator or a method, or get(index) if you want to get an array that contains all the elements, you can do so by using the toArray() method or by introducing it in ES6 Array.from() .

// 将普通数组转换成 jQuery 对象const jo = $([1, 2, 3]);jo instanceof jQuery;   // trueArray.isArray(jo);      // false// 从 jQuery 对象获取元素值const a1 = jo[0];       // 1const a2 = jo.get(1);   // 2// 将 jQuery 对象转换成普通数组const arr1 = jo.toArray();      // [1, 2, 3]Array.isArray(arr1);            // trueconst arr2 = Array.from(jo);    // [1, 2, 3]Array.isArray(arr2);            // true
Attention each/mapAnd forEach/mapThe parameter order of the callback function

JQuery defines $.fn both the above each() and the methods and definitions on the map() Array.prototype native methods forEach() and map() corresponding, their parameters are callback functions, but their callback function definition has some differences in the details.

$.fn.each()The callback definition is as follows:

Function(Integer index, Element element )

The first parameter of the callback is where the array element is located (ordinal, 0 starting from), and the second argument is the element itself.

and Array.prototype.forEach() the callback definition is

Function(currentValue, index, array)

The first parameter of the callback is the array element itself, and the second parameter is the position (ordinal) of the element. And this callback has a third argument, a reference to the entire array.

Pay particular attention to the first and second parameters of the two callback definitions, which represent the exact exchange of meaning, which is prone to errors when mixing jQuery and native code.

The same $.fn.map() is true for callbacks for and, and Array.prototype.map() because the two methods have the same name, the probability of a mistake is greater.

Attention each()/map()In the this

$.fn.each()And $.fn.map() callbacks are often used this , which this points to the current array element. Because of this convenience, JQuery does not use the element itself as the first parameter when defining reciprocate, but instead takes the ordinal as the first parameter.

But ES6 brings the arrow function. The most common function of an arrow function is to use callbacks. The arrow functions are this related to the context of the arrow function definition, rather than to the caller, as in the normal function this .

Now the problem is, if you take the arrow function as $.fn.each() $.fn.map() a callback, you need to pay special attention to this use--the arrow function this is no longer the element itself. Given this problem, it is recommended that function expressions be used as $.fn.each() callbacks to $.fn.map() maintain the original jQuery programming habits, if not necessary. If you really need to use the arrow function to refer to the context, remember to use the this second parameter of its callback definition as the element reference, not this .

// 将所有输入控制的 name 设置为其 id$(":input").each((index, input) => {    // const $input = $(this) 这是错误的!!!    const $input = $(input);    $input.prop("name", $input.prop("id"));});
$.fn.map()The returned array is not

Unlike Array.prototype.map() , $.fn.map() the return is not an array, but a JQuery object, which is a pseudo-array. If you need to get a native array, you can use toArray() or Array.from() output it.

const codes = $([97, 98, 99]);const chars = codes.map(function() {    return String.fromCharCode(this);});     // ["a", "b", "c"]chars instanceof jQuery;    // trueArray.isArray(chars);       // falseconst chars2 = chars.toArray();Array.isArray(chars2);      // true
JQuery Promise

JQuery is a $.Deferred() Promise function that is implemented through. Prior to ES6, if jquery was referenced, there was essentially no need to refer specifically to a Promise library, and jquery had implemented the basic functions of Promise.

However, although JQuery Promise has been implemented, then() it has not been implemented catch() , so it is not compatible with native Promise, but for CO or ES2017 async/await without pressure.

// 模拟异步操作function mock(value, ms = 200) {    const d = $.Deferred();    setTimeout(() => {        d.resolve(value);    }, ms);    return d.promise();}
// co 实现co(function* () {    const r1 = yield mock(["first"]);    const r2 = yield mock([...r1, "second"]);    const r3 = yield mock([...r2, "third"]);    console.log(r1, r2, r3);});// [‘first‘]// [‘first‘, ‘second‘]// [‘first‘, ‘second‘, ‘third‘]
// async/await 实现,需要 Chrome 55 以上版本测试(async () => {    const r1 = await mock(["first"]);    const r2 = await mock([...r1, "second"]);    const r3 = await mock([...r2, "third"]);    console.log(r1, r2, r3);})();// [‘first‘]// [‘first‘, ‘second‘]// [‘first‘, ‘second‘, ‘third‘]

Although the Promise of JQuery does not catch() , fail it provides event handling, which is reject() triggered when Deferred. There are also done events, triggers at Deferred, resovle() and always events, whatever the case may be.

Unlike a then() one-time event, events can register multiple processing functions, and the corresponding handlers are executed sequentially when the event is triggered. In addition, the event is not transitive, so it cannot be written at the fail() then() end of the chain.

Conclusion

In general, using jQuery in a large number of front-end code that operates the DOM can be very handy and makes the code for DOM operations easier to read. On the other hand, the new features created by native JavaScript can indeed replace some of jquery's tool functions/methods to reduce the project's dependency on jquery.

JQuery and native JavaScript should be symbiotic relationships, not mutexes. You should choose the right method at the right time, not the absolute one who will replace it.

Why use native JavaScript instead of jQuery?

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.