1. Code
  2. JavaScript
  3. jQuery

10 Ways to Instantly Increase Your jQuery Performance

Scroll to top
6 min read

This article will present ten easy steps that will instantly improve your script's performance. Don't worry; there isn't anything too difficult here. Everyone can apply these methods!

1. Always Use the Latest Version

jquery

The best way to keep up to date is to use a package manager like NPM with a bundler like Vite. This helps make it possible to update with just npm update.

1
npm install jquery

If you are not experienced with those tools or just want to stay up to date without having to update locally, you can use a CDN like JSDelivr.

1
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>

2. Minify and Combine Your Scripts

Minify

There is a lot of wasted space in JavaScript files, like tabs, spaces, long variable lines, and more. Those characters slow down website loading, as they create larger files that take longer to download and parse. Luckily, you can easily remove the extra characters by using an automated minification tool such as Terser.

Another part of this is combining scripts. Each separate resource requested by a website creates another HTTP request, which introduces more overhead. To combat this, tools called bundlers (like Vite) have been created. Bundlers automatically detect where you import various scripts and try to combine them, reducing the overhead. This works best using the new ECMAScript Modules. Another advantage of bundlers is they often also act as build tools, performing tools like minification.

3. Use For Instead of Each

Native functions are always faster than any helper counterparts. Whenever you're looping through an object received as JSON, you'd better rewrite your JSON and make it return an array through which you can loop easier.

Using Chrome DevTools or Firefox DevTools, it's possible to measure the time each of the two functions takes to run.

1
let array = new Array();
2
for (var i=0; i < 10000; i++) {
3
	array[i] = 0;
4
}
5
6
console.time('native');
7
let l = array.length;
8
for (var i=0; i < l; i++) {
9
	array[i] = i;
10
}
11
console.timeEnd('native');
12
13
console.time('jquery');
14
$.each (array, function (i) {
15
	array[i] = i;
16
});
17
console.timeEnd('jquery');
 

The above results are 2ms for native code, and 26ms for jQuery's each method. Although I tested it on my local machine, and although they're not actually doing anything (just a mere array filling operation), jQuery's each function takes over 10 times as long as the JS native for loop.

Comparison of the speed of for and $.each();Comparison of the speed of for and $.each();Comparison of the speed of for and $.each();
Time is in milliseconds

4. Give Your Selectors a Context

As stated in jQuery's documentation:

The DOM node context originally passed to jQuery() (if none was passed then context will be equal to the document). It should be used in conjunction with the selector to determine the exact query used.

So, if you must use classes to target your elements, at least prevent jQuery from traversing the whole DOM by using selectors appropriately.

Instead of

1
$('.class').css('color' '#123456');

always go for contextualized selectors in the form:

1
$(expression, context)

thus yielding

1
$('.class', '#class-container').css ('color', '#123456');

which runs much faster, because it doesn't have to traverse the entire DOM—just the #class-container element.

5. Cache. ALWAYS.

Do not make the mistake of rerunning your selectors time and time again. Instead, you should cache the results in a variable. That way, the DOM doesn't have to track down your element over and over again.

Never select elements multiple times inside a loop!

1
$('#item').css ('color', '#123456');
2
$('#item').html ('hello');
3
$('#item').css ('background-color', '#ffffff');
4
// you could use this instead

5
$('#item').css ('color', '#123456').html ('hello').css ('background-color', '#ffffff');
6
7
// or even

8
const item = $('#item');
9
item.css ('color', '#123456');
10
item.html ('hello');
11
item.css ('background-color', '#ffffff');
12
13
14
// as for loops, this is a big no-no

15
console.time('no cache');
16
for (let i=0; i < 1000; i++) {
17
	$('#list').append (i);
18
}
19
console.timeEnd('no cache');
20
21
// much better this way

22
console.time('cache');
23
const list = $('#list');
24
25
for (let i=0; i < 1000; i++) {
26
	list.append (i);
27
}
28
console.timeEnd('cache')

That's a real speed-killer!

And, as the following chart exemplifies, the results of caching are evident even in relatively short iterations.

Comparison of the speed of uncached and cached selectorsComparison of the speed of uncached and cached selectorsComparison of the speed of uncached and cached selectors
Time is in milliseconds

6. Avoid Parsing HTML

Using methods like html() can decrease performance significantly due to the need to parse HTML. This makes the browser do a lot more work, and you can replace it with methods like prepend(), append(), and after() (provided you are not inserting HTML with those either). Ultimately, the best thing to do is to use createElement() with some placement operations.

7. No String concat(): Use join() for Longer Strings

It might appear strange, but this really helps to speed things up, especially when dealing with long strings of text that need to be concatenated.

First, create an array and fill it with what you have to join together. The Array.join() method will prove much faster than the string String.concat() function.

1
let array = [];
2
for (let i=0; i<=10000; i++) {
3
    array[i] = '<li>'+i+'</li>';
4
}
5
6
$('#list').html (array.join (''));

This is due to how each method works. String.concat() is immutable, which means it returns a new copy of the string when it runs. This can sometimes be helpful, but often you do not need that, so use Array.join() instead.

8. Return False or Use preventDefault()

Sometimes, you might want to avoid the default behavior of something. For example, you might not want a link to load another page if you are loading it through Ajax. To prevent this, you generally either return false in the event handler or use event.preventDefault().

So, instead of

1
$('#item').click (function () {
2
	// stuff here

3
});

take the time to write

1
$('#item').click (function (event) {
2
	// stuff here

3
	event.preventDefault();
4
});

return false calls event.preventDefault() as well as event.stopPropogation().

9. Don't Use jQuery

This might seem odd since this is about speeding up jQuery, but it is important to include. Over the last few years, browser support for JavaScript DOM functions, the main reason jQuery exists, has improved massively. Now you can do most things with native JavaScript and know that >97% users will be able to run it.

Using native JavaScript helps in two ways. First, it speeds up website loading as jQuery is a very large script (87kb minified). Second, it speeds up actual operations, since jQuery essentially acts as an intermediary between the native DOM and your code, so by cutting jQuery out, you reduce the overhead.

For example, instead of doing this:

1
$("#class");

Do this:

1
document.querySelector("#class");

Another option is to use a jQuery alternative, which tries to mimic jQuery's API while being smaller and faster. Using one of these tools, like Cash, makes it easier to migrate your code away from jQuery. Functions still will have an overhead, but it is much smaller.

10. Bonus Tip: Cheat Sheets and Library References

jQuery API DocsjQuery API DocsjQuery API Docs

This isn't a speed-up tip, but it could end up, in a roundabout way, being one if you take the time to find your way through cheat sheets and function references. Save yourself some time and keep a cheat sheet within arm's reach.

Post thumbnail generated with Open AI's DALL-E.

This post has been updated with contributions from Jacob Jackson. Jacob is a web developer, technical writer, freelancer, and open-source contributor.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.