Quick Tips to Help You Optimize jQuery Code Like a Pro
jQuery performance issues are more common than they should be, causing dreadful load times and a poor user experience. Here are some quick tips that can help you optimize jQuery code like a pro and, in turn, your website’s performance.
Depending on the pages your jQuery is on, these tips may only save a few milliseconds here and there, but in a world where you can lose 50% of your viewers with a five second load time those milliseconds add up quickly.
1. Use the proper selector. jQuery selectors aren't all equal. The ID and Tag selectors map directly to their JavaScript method counterparts, which makes them naturally fast. As for the Class selector, this also maps to its JavaScript method but only in newer browsers. This mostly pertains to Internet Explorer as 9 is the first version to have this method. As for the selectors that don’t have JavaScript methods, if these must be used try to use the “.find()” method on one of the faster selectors. In fact, anytime you can limit the search field by using a faster selector this will help with page speeds.
2. Cache your selectors. In addition to using the proper selector, you should not repeat selectors. If a selector is going to be used any more than once you should store the results into a variable. Doing this keeps jQuery from having to search the entire DOM every time you call the selector. Say you have an unordered list that has hide/show button. Instead of using a selector inside the click function, which will cause jQuery to search the entire DOM each click, you can save the results of the selector you want to be hidden or shown in a variable and use the variable in the click function. Now jQuery only has to search the DOM once but can use the variable as many times as it wants without having to search.
3. Chain jQuery methods. This can link back to tip #2. Instead of selecting the same thing multiple times for multiple methods, just have one selector with all the methods you needs chained onto it. Almost every jQuery method returns the object it was using. This allows what allows you chain methods. Doing this keeps searches and variable accesses to a minimum.
4. DOM Manipulation. This is trickier than using the correct selectors. This is more about how you do the manipulation. Say you have a loop that will create and add the needed amount of <li>’s to a list. Instead of adding the <li> to the list with each iteration, which would involve you calling a method and using a selector (or tip #2) with every iteration, you should save the <li>’s into a variable and after they have all been created use one selection and one method to do the work.
I hope that these jQuery performance tips help. If you’re experience slow load times and have questions on how to optimize jQuery code or other aspects of your site, please don’t hesitate to contact us.