Write better jQuery
- Cache selectors:
const $menu = $('#menu');instead of searching again and again - Prefix jQuery variables with $ (
$menu) so you know they are jQuery objects - Chain methods instead of re-selecting
- Use delegation for lists and tables that change
- Put code inside
$(function () { ... })or load scripts at the end of the body - Prefer classes over many
.css()calls - Use
.text()for user input —.html()can run harmful scripts (XSS)
Performance
- Use IDs and classes in selectors; avoid very long selectors
- Build big HTML once, then
appendit once — not inside a loop - Debounce
keyupandscrollhandlers - Use
.stop()before repeated animations
Avoid conflicts
If another library uses $, wrap your code:
jQuery(function ($) {
// $ is safe here
});
WordPress loads jQuery in this "no-conflict" mode.
Common mistakes
- Loading jQuery twice or after your script
- Using old methods removed in jQuery 3:
.live(),.size(),.bind()(use.on()and.length) - Forgetting
e.preventDefault()on AJAX forms - Missing the CSRF token in Laravel AJAX requests (error 419)
Example
Example — Clean jQuery pattern
HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<input id="filter" placeholder="Filter courses">
<ul id="courses"></ul>
<script>
jQuery(function ($) {
// cache selectors once
const $list = $('#courses');
const $filter = $('#filter');
const courses = ['HTML', 'CSS', 'Bootstrap', 'Tailwind CSS', 'JavaScript', 'jQuery', 'PHP', 'Laravel'];
// build HTML once, append once
function render(term) {
const items = courses
.filter(c => c.toLowerCase().includes(term))
.map(c => $('<li>').text(c));
$list.empty().append(items.length ? items : $('<li>').text('No course found'));
}
// debounce the input event
let timer;
$filter.on('input', function () {
clearTimeout(timer);
const term = $.trim($(this).val()).toLowerCase();
timer = setTimeout(() => render(term), 200);
});
render('');
});
</script>