jQuery is often looked at synonymously with JavaScript; although jQuery is just a library wrapper around native JavaScript. While jQuery is easier to some degree, a lot of the tutorials and examples on the internet showcase code that isn’t nearly as performant as using native JavaScript APIs. Although I do not suggest you use jQuery in your application, it has its merit and advantages. Here are just two examples of how you can improve the performance of your jQuery code drastically.

Looping

jQuery promotes the use of the .each() method for looping through DOM elements. It turns out that this is actually up to 10x SLOWER than using native JS’s for loop. Why? jQuery’s each method expects a function that gets called for each iteration, while the native JS just accesses the index of the array. Stick to using the native for loop! Here is a fiddle to demonstrate this: https://jsfiddle.net/r4xk1kw3/1/

1

2

3

4

5

6

7

8

9

10

11

12

13

//jQuery

varitems=$('.selector');

items.each(function(item){

console.log(item);

});

//Native

varitems=document.querySelectorAll('.items'),

numItems=items.length;

for(varx=0;x&lt;numItems;x++){

console.log(items[x]);

}

Selecting Elements from the DOM

I’ll admit, the syntax for selecting DOM elements is much easier using jQuery, but it turns out that is is much less performant than using native JS. In fact, natively there are two ways to select elements by classname: 1) .querySelectAll() or 2) getElementsByClassName(). It turns out that getElementsByClassName() is the fastest way to get a list of elements, but jQuery’s selector engine is terribly slow. Here is a fiddle I made to demonstrate this: https://jsfiddle.net/yc09s6tf/1/

1

2

3

varitems=$('.items');// .20ms

items=document.querySelectorAll(".items");//.02ms

items=document.getElementsByClassName('items');//.002ms

But Tom, that’s so ugly! Why would I ever want to write code like that? I’ll admit, native JavaScript code can be pretty fugly sometimes. But we can add a little syntactic sugar on top of the native code, while maintaining the majority of the performance gains. Here is a little utility function you can use to implement jQuery-like selectors in your code.

1

2

3

4

5

6

7

8

9

10

11

function_(selector){

if(selector.indexOf(".")===0){

returndocument.getElementsByClassName(selector.substring(1));

}else{

returndocument.getElementById(selector.substring(1));

}

}

// USAGE

varmyClass=_('.className'),

myID=_('#myID');

So what now?

Try out the fiddles for yourself and see how big of a difference these two changes can make. jQuery is nice on the eyes, but I hope you’re no longer surprised on how much faster native JavaScript is.