4 easy ways to optimize and improve jquery performance

4 easy ways to optimize and improve jquery performance

Author: emre JavaScript jQuery

In this article, I’ll explain how to improve and optimize your script’s performance. jQuery is still very popular JavaScript library, however, many of developers do not optimize their codes.

Let’s get started!

1) Use the Latest Version

jQuery keeps improving its performance and security. It is very important to keep your script up to date.

2) Use for instead of Each

Make sure you use native functions because they are faster than

var array = new Array ();
for (var x = 0; x < 10000; x++) {
array[x] = 0;
}
console.time('native');
for (var x = 0; x < array.length; x++) {
array[x] = x;
}
console.timeEnd('native');
console.time('jquery');
$.each (array, function (x) {
array[x] = x;
});
console.timeEnd('jquery');

3) Use #IDs instead of classes

I don’t really like using #IDs in HTML, I also don’t like using !important in CSS, however, with jQuery, using IDs is faster than classes. You can run the code below in your browser console to see the difference.

console.time('class');
var list = $('#list');
var items ='<ul>';
for (x=0; x<1000; x++) {
items +='<li class="item' + x +'">item</li>';
}
items +='</ul>';
list.html (items);
for (x=0; x<1000; x++) {
var s = $('.item' + x);
}
console.timeEnd('class');
console.time('id');
var list = $('#list');
var items ='<ul>';
for (x=0; x<1000; x++) {
items +='<li id="item' + x +'">item</li>';
}
items +='</ul>';
list.html (items);
for (x=0; x<1000; x++) {
var s = $('#item' + x);
}
console.timeEnd('id');

4) Caching your jQuery selector

This is one of the best way to improve your jQuery performance and it improves your jQuery performance drastically.

As an example, the following jQuery code updates element’s CSS by adding a new color (red), changes the width and changes the text of the element (‘yada yada yada’).

$("#elementid").css("color", "red");
$("#elementid").css("width", "200px");
$("#elm elementid).text("yada yada yada");

You should use the code below instead of the code above.

var $el = $("#elementid");
$el.css("color", "red");
$el.css("width", "200px");
$el.text("yada yada yada");


Write a comment

WHO AM I?
Emre Rothzerg

Strategist.
Tech Lead.
Digital Marketer.

FOLLOW:
CONTACT:
[email protected]
HAVE A QUESTION?
JOIN NOW