Monday, 21 January, 2019 UTC


Summary

Some people say that spending time for jQuery 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.
Let’s see some ways to improve JavaScript performance for the Website
1. Always use the latest version
jQuery is always developing and improving, so make sure you are using the latest version to improve the jQuery 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
As you can clearly see above [] .join () shows the best average result. So next time write code, you can use it
var veryLongMessage = [ 'This is a long string of segments including ' , 123, ' lorem ipsum sit'].join();
instead of
var veryLongMessage = 'This is a long string of segments including ' + 123 + ' lorem ipsum sit';
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");
but this is 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; <span="" class="hiddenGrammarError" pre="" data-mce-bogus="1">i++) {</l;>
array[i] = i;
}
console.timeEnd('native');

console.time('jquery');
$.each (array, function (i) {
array[i] = i;
});
console.timeEnd('jquery');
and results
Here are some tips to optimize the JavaScript code. If you have more ideas please contact us so the next post will contain your tips and your name.
The post Tips to improve jQuery performance for websites appeared first on HelpDev.