1. Use variables appropriately
Maybe
1 document.getElementById ("MyField"). Style.backgroundcolor = "#CCC"; 2 document.getElementById ("MyField"). Style.color = "#FF0000"; 3 document.getElementById ("MyField"). Style.fontweight = "bold";
Better
1 var myField = document.getElementById ("MyField"); 2 3 myField.style.backgroundColor = "#CCC"; 4 myField.style.color = "#FF0000"; 5 myField.style.fontWeight = "bold";
Every time document.getElementById ("MyField") is called, the browser searches the DOM for an element with an ID of MyField, which is inefficient.
2. Elements try to apply all styles at once
Maybe
1 var myField = document.getElementById ("MyField"); 2 myField.style.backgroundColor = "#CCC"; 3 myField.style.color = "#FF0000"; 4 myField.style.fontWeight = "bold";
Better
1 var myField = document.getElementById ("MyField"); 2 3 myField.style.cssText = "Background-color: #CCC; Color: #FF0000; Font-weight:bold ";
For an element with ID MyField, use style to apply three different style attributes, respectively. will result in three reflux (reflow) and redraw (repaint), low efficiency, can apply all styles at once, causing only one reflow and repainting.
3. For loop traversal array
Maybe
1 var myArray = [1, 2, 3]; 2 3 for (var i=0; i < myarray.length; i++) {4 // Do something 5 }
Better
1 var i = 0,2 myArray = [1, 2, 3],3 len = myarray.lenght; 4 5 for (; i<len; i++) {6 // Do something 7 }
Each iteration of the loop, the i<myarray.length to recalculate the length of the myarray.length array, the efficiency is low.