Even though jQuery is easy to use, writing inefficient code can slow down your web application, especially when manipulating the DOM. Optimized jQuery code ensures smoother animations, faster page loads, and better responsiveness.
.on() on a parent instead of binding to thousands of child elements.Every time you run $('.class'), jQuery has to hunt through the page to find those elements. Do it once and save it in a variable.
// ❌ BAD: jQuery searches the DOM 3 separate times
$('#myButton').css('color', 'red');
$('#myButton').text('Clicked');
$('#myButton').fadeIn();
// ✅ GOOD: Search once, store reference (Cache)
var $btn = $('#myButton');
$btn.css('color', 'red');
$btn.text('Clicked');
$btn.fadeIn();
// ? PRO TIP: Prefix jQuery variables with $ to identify them easily
Compare how long it takes to access an element 5,000 times by re-selecting vs using a variable.
Result: Waiting for test...
Touching the DOM triggers layout recalculations (reflow). Avoid appending inside a loop.
// ❌ BAD: Modifies the DOM 100 times (Very Slow)
var list = $('#itemList');
for (var i = 0; i < 100; i++) {
list.append('<li>Item ' + i + '</li>');
}
// ✅ GOOD: Build a long string and touch DOM once (Very Fast)
var content = '';
for (var i = 0; i < 100; i++) {
content += '<li>Item ' + i + '</li>';
}
$('#itemList').html(content);
If you have a list with 1,000 items, binding a click event to each item uses a lot of memory. Instead, bind one listener to the parent container.
// ❌ BAD: Creates 1000 event listeners
$('li').click(function() {
$(this).toggleClass('active');
});
// ✅ GOOD: 1 listener on the parent (Event Delegation)
$('#listContainer').on('click', 'li', function() {
// 'this' refers to the clicked li
$(this).toggleClass('active');
});
Test the difference between appending inside a loop vs. appending a single string.
Result: Waiting...
Using $(this) is convenient, but native this (DOM element) is faster for simple ID or attribute checks.
// ❌ SLOWER: Wrapping 'this' in jQuery just to get ID
$('a').on('click', function() {
var id = $(this).attr('id');
});
// ✅ FASTER: Using native JavaScript property
$('a').on('click', function() {
var id = this.id; // No jQuery overhead
});
.detach(), modify it, then append it back.$('#elem').hide().css('color','red').show() to reduce lookups.$('.class') is slower than $('#container .class') (scoped search).Open your browser console (F12) and try these two loops on any webpage with jQuery loaded:
1. Run a loop that does $('body').append('.') 1000 times.
2. Run a loop that adds '.' to a string variable, then does $('body').append(str) once.
Notice the massive speed difference!