How to Optimize jQuery Code for Better Performance

jQuery is the most popular client side library, in fact almost every website uses it. It is popular because it is easy to learn, makes development quick, offers clean code and helps in implementing complex functionality with ease.  The downside is that it can also decrease the performance of websites and can result in slow loading, if not used properly. To ensure the best performance of jQuery code, one has to know and follow best practices. In this post, we list some of the most crucial tips for optimizing the performance of jQuery code.

  • Load jQuery from CDN

A content delivery network (CDN) is a system of distributed servers that delivers web pages and other web content to a user based on the geographic location of the user, the origin of the web page and a content delivery server. Loading jQuery from a CDN is a good choice, as it minimizes the loading time of your site (CDN is faster to serve the library), and it also reduces the load on your web server. Caching is another advantage with CDN. If any other sites previously visited by the user are using jQuery from CDN then the cached version will be used. It will not be downloaded again. Google CDN is the preferred CDN for jQuery:

<script src="//"></script>

You can also use jQuery CDN:

<script src="// "></script>

Notice, no protocol is specified while referencing the jQuery library. "Protocol-less" URL is the best way to reference third party content that’s available via both HTTP and HTTPS. When the protocol is omitted, the browser uses the underlying document’s protocol instead.  Otherwise, you will end up getting the mixed content warning.

  • Loading jQuery locally in case of CDN unavailability

Loading jQuery from CDN is the preferred choice, but using this method means that the jQuery code will stop working if the CDN is down. This is a rare occurrence but it happens occasionally, and in this case the jQuery library will not be loaded. The program is then required to fall back to the local version of jQuery when the jQuery library does not load from CDN. The following jQuery code checks if the jQuery is loaded from CDN. If not, then it loads the jQuery library from the “Script” folder from the website directory.

<script type="text/javascript" src="//"></script>
<script type="text/javascript">
if (typeof jQuery == 'undefined')
    document.write(unescape("%3Cscript src='Scripts/jquery.3.1.1.min.js' type='text/javascript'%3E%3C/script%3E"));
  • Don’t wait for $(document).ready()

$(document).ready() is the most common option for storing all of your jQuery code. However, in case of a large or heavy page with lots of scripts and heavy images, the document ready event may get delayed using this method. Most jQuery code doesn't need to wait for either of these things. $(document).ready() matters most when the code interacts with DOM elements that are inserted after the script is executed.  If the code doesn’t require DOM element interactions, it can be removed from $(document).ready(). Consider the following example:

$(document).on('click', '#btnClick', function() {
    console.log('Click event!!!');
$(document).ready(function() {});

Here, the click event is attached to the button via event delegation, even before 'document ready' is called. This practice can increase the performance of your website. You can read this excellent article to get more details.

  • Cache your jQuery selector

Caching can improve the performance of jQuery drastically. One should be very diligent about caching selectors correctly as it can single-handedly result in notable improvements.  As an example, the following jQuery code applies a new color (green), changes the font (“Tahoma”) and changes the text of the element (“example text”). 

$("#elm").css("color", "red");
$("#elm").css("font-family", "Tahoma");
$("#elm").text("blah blah!");

The problem with the above jQuery code is that the jQuery has to traverse the DOM three times, once for each separate element (color, font and text). Traversing the DOM is a very expensive operation. One way to reduce the number of traverses is by caching the selector. Like this:

var $elm = $("#elm1").css("color", "red");
$elm.css("font-family", "Tahoma");
$elm.text("blah blah!");

Here, the first statement caches the jQuery selector and then the next 2 statements can use the cached variable. This way, jQuery need only traverse the DOM once.  This is very useful in case of long functions where one needs to repeatedly reference the same elements. The above code can also be optimized via chaining, which is our next trick!

  • Use jQuery Chaining

Chaining is one of the most powerful features of jQuery. Chaining means connecting jQuery selectors or functions one after the other. As an example, the code we used to demonstrate caching the jQuery selector can also be optimized via chaining.

$("#elm").css({ "color": "red", "font-family": "Tahoma"}).text("example text");

In this case as well, jQuery will traverse only once to get the element. Chaining can also be used for methods or functions. Like:

$("#btnDoSomething").click(function(e) {
}).mouseover(function(e) {
    console.log("mouse over!")
}).mouseout(function(e) {
    console.log("mouse out!")

The above jQuery code attaches click, mouseover and mouseout events to the button via chaining them. Chaining makes the code look short, clean and it also results in better performance.

  • Optimize your jQuery selector

The following are some other ways to improve jQuery performance while using selectors.

  • Use ID as your selector – If possible, always use element ID as your selector instead of the HTML tag or CSS Class. As for ID selector, jQuery internally makes a call to getElementById() method of Java script which directly maps to the element. Like this:
	$("#elm").css("color", "red");
  • Do not use CSS class selector exclusively – CSS class selectors are used to select elements with a specific CSS class. There are situations when you want to interact with many DOM elements, and in these cases the ID selector can’t be used.  Performance with CSS class selector can be used, by reducing the DOM traversal time. As an example, the following jQuery code selects all DOM elements with the CSS class name “dummy” and change the background color to yellow.
$(document).ready(function() {
    $(".dummy").css("background-color", "yellow");

The above jQuery code can be improved and we can reduce the time taken for DOM traversal via adding a HTML tag name with CSS class. Like this:

$(document).ready(function() {
    $("p.dummy").css("background-color", "yellow");

The above jQuery code restricts the search element by making it specific to paragraph elements with dummy CSS class.

  • Know how selectors are executed – Before optimizing any code, it’s important to know in what fashion the code will get executed. Similarly, it’s important to also know how jQuery selectors are executed. jQuery’s selector engine, called Sizzle parses selectors from right to left. Which means, the last selectors are always executed first in case of multiple selectors in a single statement. Be very careful and specific while specifying the right side selector. Like,
$('div.container .border')

The above jQuery selector can be optimized by increasing the specificity for the right side selector. Like,

$('.container div.border')


Writing efficient and optimized code improves the overall performance of an application. All the tips mentioned above can improve the performance of your jQuery code, most notably by reducing the DOM traversal time for executing the jQuery code. DOM traversal is the most expensive process and jQuery selectors play a big role in it. jQuery is awesome but without optimized code it can result in poor application performance, so make sure you implement these tips!

Responsive Menu
Add more content here...