jQuery Best Practices and Performance Tips
Good jQuery code is easy to read and fast. These simple habits help in both.
1. Cache your selections
Every time you write $('#box'), jQuery searches the page. If you use the same element again and again, find it one time and keep it in a variable.
<div id="box"><p>Text</p></div>
// slow: the same search three times
$('#box').addClass('a');
$('#box').css('color', 'red');
$('#box').find('p').text('Changed');
// better: search one time
var $box = $('#box');
$box.addClass('b');
$box.css('color', 'blue');
$box.find('p').text('Changed again');
<div id="box" class="a b" style="color: blue;">
<p>Changed again</p>
</div>
2. Use chaining
Chaining also saves searches. See Method Chaining.
3. Write selectors in an efficient way
#idselectors are fastest.- Use
.find()from a parent you already have:$box.find('.item'). - Avoid very long and general selectors, like
$('div div ul li a'). - Use classes for groups of elements. Avoid a plain tag selector on a big page when a class is possible.
4. Change the DOM less often
Each change can make the browser do the layout again. Prepare the HTML first, and add it one time.
<ul id="list"></ul>
var html = '';
for (var i = 1; i <= 5; i++) {
html += '<li>Item ' + i + '</li>';
}
$('#list').html(html); // only one DOM change
console.log($('#list li').length);
5
5. Use event delegation for lists and dynamic content
One handler on the parent is better than a handler on each item. See Event Delegation.
6. Prefer CSS classes to inline styles
Use addClass() and toggleClass(), and put the design in the CSS file.
7. Do not mix HTML and user data
Use .text() and not .html() for text from users, to stop XSS problems. Never build HTML by adding user input in a string.
8. Always check if the element exists
Most methods do nothing if the selection is empty. It is not an error, but it can hide a mistake. If the code is important, check with .length.
9. Put scripts at the end of the page
Load jQuery and your scripts before the closing </body> tag, or use defer, so the page shows quickly.
<script src="https://code.jquery.com/jquery-3.7.1.min.js" defer></script>
10. Use the minified file and a CDN or cache
Use the .min.js file on the live site, and let the browser cache it.
11. Do not use the deprecated and removed methods
Use .on() and .off(), and the native JavaScript replacements for the removed utility functions. See jQuery 4 and Upgrading.
12. Debug with the console
console.log($('#box').length)tells if the element is found.console.log($.fn.jquery)tells the version of jQuery.- The “Network” tab shows if the jQuery file is loaded.
- The “Elements” tab shows the real HTML after your code changed it.
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |