jQuery Coding Standards & Best Practices

In jQuery, same thing can be done in several ways but the main difference between different approaches is performance. So as a developer, we need to use best approach that improves performance. In this article, I have mentioned some best practices and coding standards that can be used to improve performance.

Always use CDN

CDN Stands for Content Distribution Network or also called Content Delivery Network is a group of computers placed at various points connected with network containing copies of data files to maximize bandwidth in accessing the data. In CDN, a client accesses a copy of data nearer to the client location rather than all clients accessing from the one particular server. This helps to achieve better performance of data retrieval by client.

There are 3 CDN providers: Google, Microsoft and jQuery

Google CDN
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
Microsoft CDN
<script src="//ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script>
jQuery CDN
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
We use // instead of protocol (http/https). That is because the CDN servers support http and https. If your site has an SSL certificate, you don’t need to worry about it; it will get the file downloaded.

But, what will happen if CDN is down? Your site will not function properly. You need to make sure if that thing happens, your application still runs. We have an overcome for this issue. Load the jQuery file from CDN. Check if it's loaded or not; load it from local, if it's not yet loaded. Here's the code.

   Window.JQuery || document.write('<script src="script/localsourceforjquery"></script>')

Optimize Selectors

  1. Use ID selector $('#elementId') whenever possible. It is faster because they are handled using document.getElementById()
  2. Avoid use of class selectors $('.elementClass'). Class selectors are the slowest selectors.
  3. When using class selectors, try to avoid the element type in your selector.

    var $customers = $("div.customers"); // Slow
    var $customers = $(".customers"); // Fast
  4. Use find() function for Id -> Child nested selectors. The .find() approach is faster because the first selection is handled without going through the selector engine.

    var $customerIds = $("#customers div.id"); // Slow
    // Fast, because #customers is already selected by document.getElementById() so only div.id needs to go through selector engine
    var $customerIds = $("#customers").find("div.id");
  5. Be specific on the right-hand side of your selector, and less specific on the left.

    // Unoptimized:
    $( "div.data .gonzalez" );
    // Optimized:
    $( ".data td.gonzalez" );
  6. Avoid Universal Selectors

    $('div.container > *'); // BAD
    $('div.container').children(); // BETTER


Many times, developers use the same selector many times for performing some manipulation on elements. For example:

$('#divTest span.myClass').html('Testing');  
$('#divTest span.myClass').css('border','1px solid red');  
$('#divTest span.myClass').show();

But instead of doing this we should store this selector in a variable and use that variable wherever we need to use.

var spn = $('#divTest span.myClass');   
spn.css('border','1px solid red');  


We can perform multiple operations on the selected element at once in a single line. This is called statement chaining. It is faster than performing operations one-by-one.

Don't Use
var spn = $('#divTest span.myClass');   
spn.css('border','1px solid red');  
$('#divTest span.myClass').html('Testing').css('border','1px solid red').show();

Grouping of Selectors

Many times we need to perform same operation on multiple elements selected by different selectors. So instead of writing separate line for each selector, group those selectors and operate on the group of selectors.

Don't Use
$('p, input, #divtest').show();

DOM Manipulation

  1. Don't add elements in DOM step by step

    I saw many times when developers need to add some elements in DOM, they add them step by step but it is not a good practice because while manipulating DOM, there is a cost behind the scene. If you need to add some elements to the DOM then form the entire HTML first, then add to the DOM, instead of appending the HTML step-by-step.

    var employees = [  
    {Id:1, FirstName: "Manish", LastName:"Banga"},  
    {Id:2, FirstName: "Sachin", LastName:"Kumar"},  
    {Id:3, FirstName: "Jey", LastName:"Cook"},  
    {Id:4, FirstName: "Ange", LastName:"Koko"},  
    var div = $('#divResult');
    Don't Use
    $.each(employees, function(k,v){  
    div.append('<td>' + v.Id + '</td>');  
    div.append('<td>' + v.FirstName + '</td>');  
    div.append('<td>' + v.LastName + '</td>');  
    var html = '<table>';
    $.each(employees, function(k,v){  
    html += '<tr>';
    html += '<td>' + v.Id + '</td>';
    html += '<td>' + v.FirstName + '</td>';
    html += '<td>' + v.LastName + '</td>';
    html += '</tr>';
    html += '</table>';
  2. Detach Elements to Work with Them

    You should avoid manipulating DOM as much as possible because DOM manipulation is slow. jQuery introduced detach() in version 1.4 to help address this issue, allowing you to remove an element from the DOM while you work with it.

    Always detach any existing element before manipulation and attach it back after manipulating it.

    var table = $( "#myTable" );
    var parent = table.parent();
    // ... add lots and lots of rows to table
    parent.append( table );
  3. Try to avoid use of append() function.

    Use string concatenation or array.join() in place of .append()

  4. Don’t Act on Absent Elements

    If you're trying to run a lot of code on an empty selection then there is not any notification for telling you that you are working on empty selection. It will proceed as though nothing's wrong. It's up to you to verify that your selection contains some elements.

    // Bad: This runs three functions before it
    // realizes there's nothing in the selection
    $( "#nosuchthing" ).slideUp();
    // Better:
    var elem = $( "#nosuchthing" );
    if ( elem.length ) {

Use Style for Changing CSS on Many Elements

For changing the style of elements we use css() and it works fine if we are changing the CSS of fewer elements. But we need to change style of more than 20 elements using .css() then it will slow down page performance. A style in the head tag will provide better performance in this case.

Don't Use
$( "div" ).css( "color", "#0769ad" );
$("<style type=\"text/css\"> div{color: #0769ad;}</style>")
    .appendTo( "head" );

Group your CSS

If you need to apply set of styles on same style then it is recommended that group all css styles and apply on element once.

Don't Use
var div = $('#divTest');  
div.css('border', '1px solid black');   
div.css('color', 'red');   
div.css('backgroun-color', 'pink');   
div.css('display', 'block');
var div = $('#divTest');
div.css({'border': '1px solid black', 'color': 'red', 'backgroun-color': 'pink', 'display': 'block'});