📜 ⬆️ ⬇️

Vanilla JS vs jQuery 2.0

The article is inspired by the Vanilla.js framework.

The era of old browsers goes into oblivion, it is unlikely that now there will be a conscious person using ie6,7,8, evil for the developers and contrary to technical progress. Perhaps only if necessary, for example, the corporate system is written under IE6, or lazy admins mock users and do not want to update / install new versions. However, the usage statistics of these browsers inexorably tend to zero. Actually, the new version of jQuery 2.0, refused to support outdated browsers (IE 6-8). And then with the release of jQuery a question arose, but why then need jQuery?

My opinion is that people use jQuery only out of habit, or simply do not know the basic javascript things and the browser API that it provides. What to conceal, he wrote on jQuery before he mastered javascript ...
But in the end, vanilla prevailed, for which there were many reasons, but for some more detailed below.

Let's analyze the main features of jQuery:

Sizzle Cross-Browser CSS Selector Engine

Well, this is quite a great thing, but for what? I think it’s not just me who met projects / plugins that use jQuery in 3 places, such as $ ('# my_element'). Hide ().
And for this, people use jQuery and drag it in dependencies? Well, that's their choice ...

What does vanilla offer in this case?
For javascript developers, document.querySelectorAll is familiar, embedded in the browser and appeared even in IE8. can i use
But here someone may feel sorry for the characters to write this every time, since javascript is a flexible language and allows you to write different constructions, which you can use.
')
var $ = document.querySelectorAll.bind(document) //  ,  bind    bind(  ) var $ = function(selector){ return document.querySelectorAll(selector) } //   ,   querySelector 


Manipulating and navigating the DOM tree

For many jQuery users, it remains a mystery what happens when they write $ ('selector') or manipulate the DOM.
In all of its methods, jQuery returns its jQuery wrapper object, which allows library users to write chains from jQuery calls.

I think that the picture in projects is familiar to many:
  $(this).next().val(ui.item.id); $(this).next().next().val(ui.item.line); $(this).next().next().next().val(ui.item.id); $(this).next().next().next().next().next().val(ui.item.person.birth_date); $(this).next().next().next().next().next().next().next().val(ui.item.person.weight); $(this).next().next().next().next().next().next().next().next().val(ui.item.person.height); $(this).next().next().next().next().next().next().next().next().next().val(ui.item.person.name_translit); 

Of course, many will say that this code has a direct route to the site of the same name , and they will be right. Ideally, of course, next (selector). But you have to wonder why someone wrote it that way? But this is typical behavior for jQuery objects. But if you do not find fault with the code itself, because instead of next there could be various manipulations with the DOM (css, attr, find ...), recorded in the call chain, the question arises: why is this code obfuscation?

Apparently, some people write code for the machine ... and not for people who will get this code.

Similar behavior exists for methods of working with jQuery objects (node ​​list, array), methods: each, map, etc. The need for these methods was when jQuery implemented them for old IE. All modern browsers have native methods for working with arrays, forEach, map ...

As for jQuery itself, sample code:
 $([1,2,3]).each(function(index, element){ //do something }) $([1,2,3]).each(function(i,e){ console.log(this===e) }) // 2 


Several remarks at once, the array element is passed by the second argument, that in the iteration through the list is stupid and illogical, because the iterator itself is needed more often than the index, and the index is not needed at all, but there is this which refers to the current element, and in this case, creating A new instance of the Number variable ... as shown in Example 2, it is obvious that this and the attribute are not the same thing. If you try to compare this with a number, without conversion, you get false.
javascript allows, but if everyone does what he wants, the world will obviously not get any better.

And an example of vanilla:
 [1,2,3].forEach(function(element, index){ //do something }, [, context]) 

Parameters in a logical order, it is possible to set the execution context (this), without making unnecessary closures.

There is a fairly extensive API for manipulating DOM objects, you can read it on MDN .

Developments

jQuery provides a seemingly convenient EventListener, allows you to add events to elements, selectors, and even elements that do not exist on the page (live -> on), unfortunately, are absolutely indestructible and do unnecessary manipulations. For example, hang the event on the page where the item is missing.

 $(function(){ $('.elements').bind('event', callback) }) 


If there is no element on the page, nothing will happen; in the development process, you can make a mistake in the class name, and jQuery successfully handles this case, and you will search further, why the button / link event does not work until you notice a typo. Or a similar situation when the element is present on different pages, but the first one needs an event, and the second does not. Here you have to improvise, change class names or make conditional selects.

As for live methods, are you sure that you write and know how it works? Essentially, the elements on the page are not taken from the air, nothing prevents to hang the events, for example, as a result of an ajax request or on the event that caused the appearance of the element. Calling an event handler will speed up several times.

jQuery here is just syntactic sugar , no more.

In earlier versions of IE, events were attached using attachEvent, which made work difficult, and jQuery, in turn, did everything automagically, but now all browsers support EventListener
 element.addEventListener('event', callback) 

which can always be overridden by writing a short method or a convenient wrapper over the events (on lines 20), if you have enough javascript knowledge.

Visual effects

A set of simple tools for effects that are not always needed ... Alternative? write yourself, just what you need, about this in the article about vanilla. Certainly not a reason to fence bicycles, but not to pull the whole library for the sake of one method.
 var s = document.getElementById('thing').style; s.opacity = 1; (function fade(){(s.opacity-=.1)<0?s.display="none":setTimeout(fade,40)})(); 

jQuery
 <script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script> $('#thing').fadeOut(); </script> 


AJAX

It is difficult now to imagine a site without ajax. But what makes jQuery so special in this case?
In previous versions, it was obvious that ajax request should be cross-browser and implemented in different ways, depending on the user's browser. But this is in the past, now jQuery only adds syntactic sugar for those who really do not know how to create an XMLHttpRequest object. It is difficult to argue, much shorter to write down:

 $.ajax({ method: 'get', url: 'http://habrahabr.ru/', success: function(data){ // ? } }) 

without considering jQuery itself, it seems to be short, but modern browsers support native XMLHttpRequest:

 var r = new XMLHttpRequest(); r.open("GET", "http://habrahabr.ru/", true); r.onreadystatechange = function () { if (r.readyState != 4 || r.status != 200) return; // ? }; r.send(); 

which in itself is not much beyond jQuery.ajax.

Javascript plugins

An extensive library of plug-ins on jQuery, sliders, scrollers, etc. ... Library clones for every taste, you can find dozens or even hundreds of identical plug-ins in the search, differing in implementation and / or author.
$ ('selector'). do_all_as_nado () solves many questions, but which library authors can give you a 100% guarantee, and if something goes wrong, the customer is clearly not interested in listening to Vasya Pupkin, who has fixed the bug.

Of course, Vanilla is not a framework, but the most javascript that allows you to do everything that is necessary.
It’s hard to imagine how jQuery will help if you need to write some class in javascript or you don’t find the necessary one, and you may not even have heard what prototype is (not a framework) and what it is for.

Summary

As a result, it is impossible to say that jQuery is a heavy framework (33.6 KB compressed) in our digital age of unlimited Internet and mobile devices with a memory larger than 1GB. But in most cases it is absolutely useless appendage that slows down the page many times (as the benches show about 50), without which you can do. A completely different situation with plugins. It seems that the developers do not want to think at all, the new task is a new plugin in the project. As a result, the number of jQuery plug-ins (which can pull different versions of jQuery) inflates js to 0.5 MB, or even more ...

jQuery provides syntactic sugar, to many client javascript constructs, but at the cost of performance, it seems everyone decides for himself what to sacrifice, either time to develop or product quality.

Known point of view of Niklaus Wirth , which is shared by part of the programming community: according to her, any extension of the language, not caused by necessity, worsens it, as it leads to complication of the translator and, accordingly, to a decrease in its reliability and performance. At the same time, the complexity of language learning and the complexity of program maintenance increase. In addition, the mere fact of having additional syntax often plays a provocative role: it encourages the programmer to resort to different syntactic tricks instead of deeper analyzing the task and implementing more efficient algorithms. [ Wiki ]

Sometimes it is necessary to think about what you are doing, the work of the programmer is like this - think, here and try.
The point is not to abandon jQuery and write on vanilla, just do not overestimate its capabilities, mindlessly using where it is necessary and not necessary, I think everyone remembers " how to add two numbers in javascript ".

PS Most likely, many stones from jQuery users and comments that it (the framework) reduces development time will fly to me, but I want to hope for the consciousness of people and believe that programmers know their work and know how to think with their heads.

Source: https://habr.com/ru/post/201686/


All Articles