X

LATEST #JQUERY NEWS

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="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

You can also use jQuery CDN:

<script src="//code.jquery.com/jquery-3.1.1.min.js "></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="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></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"));
}
</script>
  • 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) {
    console.log("click!");
}).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:
$(document).ready(function(){
	$("#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')

Conclusion

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!

Recently Published

article image
»

15 Newest jQuery plugins for responsive website

Due to the proliferation of smartphones and tablets, responsive ...

article image
»

How to use Redux with jQuery

State management is one of most integral parts of any software and a ...

article image
»

Fade HTML Table Row on Hover Using jQuery

HTML tables are the ideal choice for displaying data in tabular form. ...

article image
»

Drag and Drop HTML Table Rows Using jQuery

HTML tables are the preferred UI option for displaying data. Sorting, ...

article image
»

Top 5 Best JavaScript Template Engines

Template engines help in the decoupling of HTML and JavaScript code ...

article image
»

3 jQuery/JavaScript Plugins for Push Notifications

Push notifications started from the mobile business but this ...

article image
»

Create Smooth Animation Using jQuery’s “stop()”

Making Quick Work jQuery’s animate() method is a quick way to ...

article image
»

Check all checkboxes in HTML table using jQuery

HTML tables are a very handy and useful element. They can adapt to ...

article image
»

Changing images in a loop on hover using jQuery

Why use this Function? Changing images in a loop on mouse over is a ...