Despite being one of the most popular JavaScript libraries today jQuery has its shortcomings too.
If used carelessly, it can lead to performance issues. This post will list some of the best practices in using jQuery that will help us avoid them.
- Limit DOM Interaction
There is a cost when manipulating the DOM tree using jquery. So try to limit interaction with the DOM. Lets take a look at the below code:
123456var fruits = ["mango", "banana", "guava", "strawberries", "watermelon", "apple", "grapes","oranges"],var list = $("ul.fruitsList");$.each(fruits, function(index, value) {list.append("<li id=" + index + ">" + value + "</li>");});
Well, no points for guessing whats wrong here. This piece of code works just fine, since the fruits array is of 8 items only. But suppose we had a list of 1000 items, it would really mess up the speed of the website because we are repeatedly appending elements to the DOM, inside a loop.
Instead of doing this, we can build up a html first and then append it to the DOM.
123456789// Dynamically building an unordered list from an arrayvar fruits = ["mango", "banana", "guava", "strawberries", "watermelon", "apple", "grapes","oranges"],var list = $("ul.fruitsList");var futureItems = "";$.each(fruits, function(index, value) {futureItems += "<li id=" + index + ">" + value + "</li>";});list.append(futureItems); - Handling Events on Selectors
Though jQuery can select elements very quickly, it is not necessary to search for the same elements many times.
12345// Selecting the same element multiple times here.$('.lump-sum-dist').keyup(this.calculateLumpSumSplit).bind(this);$('.lump-sum-dist').change(this.validateLumpsumAmount);$('.lump-sum-dist').keyup(this.calculateLumpSumTotal);$('.lump-sum-dist').keypress(window.cred.util.isNumber);
123456// better wayvar contextElem = $('.lump-sum-dist');contextElem.keyup(this.calculateLumpSumSplit).bind(this);contextElem.change(this.validateLumpsumAmount);contextElem.keyup(this.calculateLumpSumTotal);contextElem.keypress(window.cred.util.isNumber); - Optimize Selectors
With the first approach, jQuery queries the DOM using document.querySelectorAll(). With the second, jQuery uses document.getElementById(), which is faster, although the speed improvement may be diminished by the subsequent call to .find().
1234// Fast:$( "#container div.hello" );// Super-fast:$( "#container" ).find( "div.hello" );
Specificity:
Be specific on the right-hand side of your selector, and less specific on the left.
1234// Unoptimized:$( "div.data .hello" );// Optimized:$( ".data td.hello" ); - Detach Elements to Work with Them
The DOM is slow; you want to avoid manipulating it as much as possible. 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.
12345var table = $( "#myTable" );var parent = table.parent();table.detach();// ... add lots and lots of rows to tableparent.append( table ); - Use Stylesheets for Changing CSS
If you’re changing the CSS of more than 20 elements using .css(), consider adding a style tag to the page instead for a nearly 60% increase in speed.
12345// Fine for up to 20 elements, slow after that:$( "a.login" ).css( "color", "#0769ad" );// Much faster (though, best would be, if we write the css in a separate css file):$( "<style type=\"text/css\">a.login { color: #0769ad }</style>").appendTo( "head" ); - Avoid $( window ).load()
The $( document ).ready() is fired when a page’s own DOM is loaded, but not external assets like images and stylesheets while $( window ).load() is fired when everything a page is made up of, including its own content and its sub-resources are loaded.
So, if you’re writing a script that relies on a page’s sub-resources, like changing the background color of a div that’s styled by an external stylesheet, only then use $( window ).load() else it’s better to stick to $( document ).ready().