📜 ⬆️ ⬇️

Migration option from jQuery to pure javascript

The jQuery library was created in 2006 to fill in the missing Javascript functionality. Since then, the latter has progressed sufficiently in its development, so that developers can do without jQuery, the main problem of which is performance.



On Habré there were several articles with objective measurements of the "inhibition" of JQuery on selector queries.
// jQuery 2.0 var c = $("#comments .comment"); 
4,649 ms
 // jQuery 2.0 var c = $(".comment"); 
3,437 ms
 // native querySelectorAll var c = document.querySelectorAll("#comments .comment"); 
1,362 ms
 // native querySelectorAll var c = document.querySelectorAll(".comment"); 
1,168 ms
 // native getElementById / getElementsByClassName var n = document.getElementById("comments"); var c = n.getElementsByClassName("comment"); 
107 ms
 // native getElementsByClassName var c = document.getElementsByClassName("comment"); 
75 ms
(run in a cycle of 10,000 times)
')
There are a lot of good descriptions of analogs of JQuery functions on pure Javascript-e in the network - for example, here .

But the power of jQuery is in the brevity and beauty of its expressions. It is even psychologically difficult to rewrite the existing code, changing the elegant $ () into multi-line constructions.

Let's try, as far as possible, to leave the jQuery language, [partially] replacing it with itself. To do this, we only need to either override the $ () function, or replace (which is better) with our own - let it be $ jqr (). It will also return an object, but already “native” and not burdened with unnecessary jQuery functions.

Code example:

 <html> <body> <p id="message"></p> </body> </html> 

Jquery code:

 $("#message").html("Hello world!"); 

Changes to:

 $jqr("#message").html("Hello world!"); // JQuery Replacement function $jqr(sel) { return new JQR(sel); } class JQR { constructor(sel) { this.sel = sel; this.elements = document.querySelectorAll(sel); } html(str) { for (var i = 0; i < this.elements.length; i++) { this.elements[i].innerHTML = str; } } } 

In the class constructor it is desirable to parse sel in order to more efficiently use querySelectorAll (), getElementsByClassName () and getElementById ().

Thus, we can implement only the functions we need in the JQR class, without going beyond the standard Javascript, and not really touching the existing code.

It is not necessary to even completely get rid of jQuery - partial optimization will already give results.

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


All Articles