jQuery is amazing JS Library that makes JavaScript easy to write. All developers from beginners to experts love this library. But as Winston Churchill said “with great power comes great responsibility” — that applies to jQuery also.

The unfortunate downside of jQuery is that you can end up writing really f*c*ing bad JavaScript. This not only slows down the web pages but also makes the life of the developers miserable.

Thankfully, there are a few very simple things anyone can add into their jQuery workflow, and that can clear up a lot of basic problems. Some biggest problems are:

inefficient selectors poor event delegation clunky DOM manipulation.

We’ll tackle all three of these and hopefully you’ll walk away with some new jQuery batarangs to toss around in your next project.

1. Selecting Elements

jQuery is great when selecting DOM elements. There are many ways to do it — like with id, class, find, parent, children, etc. However, a surprising number of web developers are unaware that these ways are not equal — some are fast while some are slow. There are good numbers of performance difference between them.

Example — How to find all anchor tags inside a div in the fastest manner?

Option 1: $(“#myDiv a”); Option 2: $(“#myDiv”).find(“a”); Option 3: $(“.anchorClass”);

You will be surprised to know that Option 2 is the fastest. Therefore use the .find() method whenever possible.

From fastest to slowest ways

The methods from the fastest to the slowest speeds are:

a. $(“id”)

The id selector is the fastest. The reason being there can be only one element with a particular id.

b. $(“p”); $(“a”); $(“input”);

Selecting elements by tag name is also quite fast.

c. $(“.class”);

Selecting elements by class is slow since there can be multiple elements that have the same class. If your web page has over 50 elements with the same class then you are doing more wrong by using the class selector.

d. $(“[attribute=value]”);

Attribute selectors are slowest. The below example of attribute selector selects all paragraph elements having title attribute having value starting from ‘Hello’ string.

$(“p[title |=‘Hello’]”)

2. Use latest version of jQuery, minified version, and from CDN

a) jQuery is in constant development and improvement. New improvements are added in every new version of jQuery. If you are using version 2.2.4, which was released 2 years back, then its time you should switch to the 3.3.1 version which is the latest version at present.

Your codes will execute faster on the 3.3.1 version then in the 2.2.4.

Also note that the jQuery development team phases out old and unwanted methods from time to time. Therefore switching to newer version can sometime break your code.

Examples of some methods that were phases out:

1) .live() method was removed from version 1.7.

2) .load() method which was used for binding an event handler to the “load” JavaScript event, was removed from version 1.8.

Note:- Now there is only one .load() method in jQuery. This is the AJAX method called jQuery Load Method.

3) .attr() method no longer works for Checking and Unchecking of Checkboxes. This happens from jQuery version 1.6. Now you have to use .prop() method for checkbox checking or unchecking.

4. unbind() method used for attaching event handler from the elements was removed from jQuery version 3.0.

This list is very large.

b) Use minified jQuery version on production. This version is also called as compressed version of jQuery.

I compared the sizes of these 2 versions of jQuery 3.2.1. The uncompressed version size is 262 KB while the minified version size is just 65 KB.

You get the point here. Use minified version on your production server always.

c) Use jQuery CDN to load your jQuery in your website. It will greatly reduce the load time of the page since jQuery is now loaded from a CDN data server than from your website.

If you want to fully understand how CDN works then see this tutorial — What is CDN.

There are also many other useful feature of CDN which gives you ‘security’ and ‘load balancing’.

3. Load jQuery not from page head but from the Body end

Developers usually add jQuery link on the page head.

<head>

<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”></script>

</head>

I would tell you to put it before the body end tag.

<body>

…….

…….

<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”></script> <script>

$( document ).ready(function() {

console.log( “ready!” );

});

</script>

</body>

Yahoo Performance Article also suggests this.

The problem caused by scripts is that they block parallel downloads. Browsers download no more than two components in parallel per hostname. So When you put scripts in <head> tag, the browsers goes for them, thereby keeping other stuff on hold until scripts are loaded, thus leading to slow loading of the page. This is why you should put scripts at the bottom.

4. Store result of selector inside a variable

Never select elements again and again. Instead, you should cache it in a variable. That way, jQuery does not have to track down your element over and over again.

Never selects element everytime in the loop. The below code is very bad in terms of performance.

//Bad approach

for (var i=0; i<1000; i++) {

$(‘#myItem’).append(i);

}

Change the above code to store the selected item in a variable then use that variable inside the loop:

//Good approach

var item = $(‘#myItem’);

for (var i=0; i<1000; i++) {

item.append(i);

}

5. Use jQuery On method to attach multiple event handlers

The jQuery On method is very useful when doing coding. I you are attaching multiple events to an element then the code will become long.

Take for example I have attached 2 events on my paragraph element. These events are — mouseover & mouseout.

The code becomes:

$(“p”).mouseover(function(){

$(this).addClass(“highlight”);

}); $(“p”).mouseout(function(){

$(this).removeClass(“highlight”);

});

I can combine these 2 event together with .on() method.

$(“p”).on(“mouseover mouseout”, function(){

$(this).toggleClass(“highlight”);

});

My code becomes very small here.

So do not miss any change to reduce the number of lines in your code.

6. Filtering element of the array with jQuery Grep Method

jQuery Grep method is amazing, I really like it because of it marvellous power. When you are dealing with array make use of it to filter out element from it.

See the .grep() usage in the code below:

var arr = [1, 2, 3, 4, 5, 6, 6, 1, 7];

newarr = $.grep(arr, function (n, i) {

return (n > 4);

});

console.log(“Array is [“ + newarr + “]”);

Here you will get [5,6,6,7] for the newarr value.

I know, once you understand the .grep() method then you can go and will use it in your code.

Conclusion

I hope you like the points that I have listed above, for doing proper jQuery optimization. If really like this article then please me few claps, it will surely bring a smile to my face and will motivate me to create & publish new article on Medium every week.