jQuery: Improve performance for websites

2

Improve jQuery: Some people say that spending time developing for performance is not worth it because when upgrading hardware is often a cheaper alternative. But when we know how to optimize the code, it will save many times more than the new hardware upgrade.

Here, I would like to introduce to you some ways to improve JavaScript performance for the Website

1. Always use the latest version

jquery latest version

jQuery is always developing and improving, so make sure you are using the latest version to improve the performance of the program.

2. Optimize the loop

Loops like for, while, by while are often used a lot in JavaScript. If we optimize all loops, the page loading speed will be significantly improved.

The loop is used to repeat the execution of a code many times, if the loop contains complex statements, the execution speed will slow down. Therefore, in order to increase execution speed, it is recommended to replace complex statements with simpler statements.

  • For example, the code has low performance:
for (var i = 0; i < arr.length; i++) {
    arr[i] = i;
}

For example, high performance code:

var n = arr.length; 
for (var i = 0; i < n; i++) {
    arr[i] = i; 
}

3. Processing string

Take a look at some of the following simple concatenation methods

var foo = ""; 
foo = foo + bar; 
foo +=   bar; 
[foo, bar].join( ); 
foo.concat( bar );

and compare results

Results of writing better code in jquery

As above clearly [] .join () shows the best average result. So next time write code, please use it

var  veryLongMessage  =  [  'This is a long string of segments including '  ,  123 ,  ' nam lien tiep voi nhau' ] . join ( ) ;

instead of

var veryLongMessage = 'This is a long string of segments including '  + 123 + ' in succession';

4. Restrict access to HTML elements

The commands that access HTML elements have a very slow execution speed. If you want to access the same element multiple times, you should access it once and then save it to a variable for reuse.

  • For example, the code has low performance:
$("#demo").html("a"); 
    $("#demo").html("b"); 
    $("#demo").html("c"); 
    $("#demo").html("d");

For example, high performance code:

var demo = $("#demo"); 
    demo.html("a"); 
    demo.html("b"); 
    demo.html("c"); 
    demo.html("d");

5. Use for or while instead of each

Let’s see the following example

var array = new Array();
for (var i = 0; i < 10000; i++) {
    array[i] = 0;
}
 
console.time('native');
var l = array.length; 
for (var i = 0; i < l; i++) {
    array[i] = i;
}

console.timeEnd('native');

console.time('jquery');
$.each(array, function (i) {
    array[i] = i;
}); 

console.timeEnd('jquery');

And results

Results of writing better code in jquery 2

Source: https://techtalk.vn/cai-thien-hieu-suat-jquery-cho-website.html

Share This:

Powered by FrontNet