Goal: allow the rendering engine to start rendering a table before it has received all the data
Use table-layout:fixed
Explicitly define a COL element for each column
Set the WIDTH attribute on each col
Close Your HTML Tags to Speed Up Parsing
Regular expression
Use regular expression literals.
Eg: if (/loaded|complete/.test(status)) {...}
Stick to simple patterns
In IE, Use Array.join(“”) rather than string concatenation
Miscellaneous Tips
In case of changing lot of styles in js, try swapping styleclasses.
More maintainable: change the CSS class name of an element. obj.className=‘<class>’;
Consider using the onmousedown event instead of the onclick event
Document Tree Modification.
InnerHTML Way is Faster than Usal Way
Speed Up Javascript
There are four main reasons why a script can take too long to execute
Too much happening in a loop.
Too much happening in a function.
Too much recursion.
Too much DOM interaction.
Too much happening in a loop
for(var i=0; i < items.length; i++){
process(items[i]);
}
function chunk(array, process, context){
var items = array.concat(); //clone the array
setTimeout(function(){
var item = items.shift();
process.call(context, item);
if (items.length > 0){
setTimeout(arguments.callee, 100);
}
}, 100);
}
Too much happening in a function
function bubbleSort(items){ for (var i=items.length-1; i >= 0; i--){ for (var j=i; j >= 0; j--){ if (items[j] < items[j-1]){ var temp = items[j]; items[j] = items[j-1]; items[j-1] = temp; } } } }
function bubbleSort(array, onComplete){ var pos = 0; (function(){ var j, value; for (j=array.length; j > pos; j--){ if (array[j] < array[j-1]){ value = data[j]; data[j] = data[j-1]; data[j-1] = value; } } pos++; if (pos < array.length){ setTimeout(arguments.callee,10); } else { onComplete(); } })(); }
Too much happening in a function
function fibonacci (n) { return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); };
function memoizer(memo, fundamental) { var shell = function (n) { var result = memo[n]; if (typeof result !== 'number') { result = fundamental(shell, n); memo[n] = result; } return result; }; return shell; };
var fibonacci = memoizer([0, 1], function (recur, n) { return recur(n - 1) + recur(n - 2); });
fibonacci(40);
Too much recursion
function merge(left, right){ var result = []; while (left.length > 0 && right.length > 0){ if (left[0] < right[0]){ result.push(left.shift()); } else { result.push(right.shift()); } } return result.concat(left).concat(right); }
//recursive merge sort algorithm
function mergeSort(items){ if (items.length == 1) { return items; } var middle = Math.floor(items.length / 2), left = items.slice(0, middle), right = items.slice(middle); return merge(mergeSort(left), mergeSort(right)); }
//iterative merge sort algorithm
function mergeSort(items){ if (items.length == 1) { return items; } var work = []; for (var i=0, len=items.length; i < len; i++){ work.push([items[i]]); } work.push([]); //in case of odd number of items for (var lim=len; lim > 1; lim = (lim+1)/2){ for (var j=0,k=0; k < lim; j++, k+=2){ work[j] = merge(work[k], work[k+1]); } work[j] = []; //in case of odd number of items } return work[0]; }
Too much DOM interaction
Reflow happens at various points in time:
Initial page load.
Browser window resize.
DOM nodes added or removed. (When you add or remove a DOM node. )
Layout styles applied. (When you apply a style dynamically (such as element.style.width="10px").)
Layout information retrieved. (When you retrieve a measurement that must be calculated, such as accessing offsetWidth, clientHeight, or any computed CSS value (via getComputedStyle() in DOM-compliant browsers or currentStyle in IE), while DOM changes are queued up to be made.)
perform as many changes as possible outside of the live DOM structure
for (var i=0; i < items.length; i++){ var item = document.createElement("li"); item.appendChild(document.createTextNode("Option " + i); list.appendChild(item); }
var fragment = document.createDocumentFragment(); for (var i=0; i < items.length; i++){ var item = document.createElement("li"); item.appendChild(document.createTextNode("Option " + i); fragment.appendChild(item); } list.appendChild(fragment);
remove a node from the live DOM before operating on it
list.style.display = "none";
for (var i=0; i < items.length; i++){
var item = document.createElement("li"); item.appendChild(document.createTextNode("Option " + i);
list.appendChild(item); }
list.style.display = "";
change the class using JavaScript rather than applying individual style changes manually
var divs = document.getElementsByTagName("div");
for (var i=0; i < divs.length; i++){ //infinite loop document.body.appendChild(document.createElement("div")); }
var divs = document.getElementsByTagName("div");
for (var i=0, len=divs.length; i < len; i++){ //not an infinite loop document.body.appendChild(document.createElement("div")); }
Fastest way to build an HTML string
String concat
var arr = ['item 1', 'item 2', 'item 3', ...], list = ''; for (var i = 0, l = arr.length; i < l; i++) { list += '<li>' + arr[i] + '</li>'; } list = '<ul>' + list + '</ul>';
Array pushing
var arr = ['item 1', 'item 2', 'item 3', ...], list = []; for (var i = 0, l = arr.length; i < l; i++) { list[list.length] = '<li>' + arr[i] + '</li>'; } list = '<ul>' + list.join('') + '</ul>';
Native join
var arr = ['item 1', 'item 2', 'item 3', ...]; var list = '<ul><li>' + arr.join('</li><li>') + '</li></ul>';
Javascript good practice
Always use “var” for declaration.
Feature detect rather that browser detect.
Use Object literal notation:
Var order = {
mode: ‘default’,
obj : { id:’1’, val:’10’},
array1 : [‘1’, ‘2’, ‘3’],
show : function(elToshow) {
}
}
Use square bracket notation
MyObject[“property”] rather than MyObject.property
Use dot notation for standard properties of objects
Square bracket notation to access properties which are defined as objects in the page.
0 comments
Post a comment