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:
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.
- Handling Events on Selectors
Though jQuery can select elements very quickly, it is not necessary to search for the same elements many times.
Better way123456// 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().
Be specific on the right-hand side of your selector, and less specific on the left.
- 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.
- 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.
- 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().