Performance optimization


##Performance optimization

Avoid unnecessary DOM operations

It is expensive for the browser to traverse DOM elements. The simplest solution to optimize DOM tree query is to save it in a variable when an element appears multiple times to avoid querying the DOM tree multiple times.

// Recommended
var myList = "";
var myListHTML = document.getElementById("myList").innerHTML;

for (var i = 0; i < 100; i++) {
  myList += "<span>" + i + "</span>";
}

myListHTML = myList;

// Not recommended
for (var i = 0; i < 100; i++) {
  document.getElementById("myList").innerHTML += "<span>" + i + "</span>";
}

Cache array length

Loops are undoubtedly a very relevant part of JavaScript performance. By storing the length of the array, you can effectively avoid recalculating each loop.

Note: Although modern browser engines will automatically optimize this process, don't forget that there are still older browsers.

var arr = new Array(1000),
    len, i;
// Recommended - size is calculated only 1 time and then stored
for (i = 0, len = arr.length; i < len; i++) {

}

// Not recommended - size needs to be recalculated 1000 times
for (i = 0; i < arr.length; i++) {

}

Asynchronous loading of third-party content

When you cannot guarantee that embedding third-party content such as Youtube videos or a like/tweet button will work properly, you need to consider using asynchronous loading of these codes. Avoid blocking the entire page load.

(function() {    var script,
        scripts = document.getElementsByTagName('script')[0];    function load(url) {
      script = document.createElement('script');
      script.async = true;
      script.src = url;
      scripts.parentNode.insertBefore(script, scripts);
    }

    load('//apis.google.com/js/plusone.js');
    load('//platform.twitter.com/widgets.js');
    load('//s.widgetsite.com/widget.js');

}());

Avoid using jQuery to implement animation

1. It is forbidden to use slideUp/Down() fadeIn/fadeOut() and other methods;

2. Try not to use the animate() method ;