Tuesday, 14 October 2008

JavaScript: JavaScript Better Practices

There are some tips to make your JavaScript code runing faster.
  • Use "var" whenever a variable is to be declared
  • Reduce scopes (Try avoiding nesting functions or loops)
  • Avoid string concatenation, use Array instead - “push” each pieces of the string into array and then use “join” to get the complete string
  • Use less DOM element concatenation - concatenate everything into string/Array first, then assign to the DOM element
  • Introduce function delegate. This one is worth mentioning. When calling a function in a loop, delegate before the loop because JavaScript interpreter will use the function then as local variable and will not lookup in its scope chain for the function body in each iteration. Code:
    var delegate = myFunc; // myFunc is the function
    delegate(el1);
  • Introduct DOM elements and function caching. Similar to function delegation. Example:
    var divContentAppendChild = document.getElementById("div1").appendChild;

    for (var i = 0; i < count; i++)
        divContentAppendChild(element[i]);
  • Avoid using switch if possible, as JavaScript interpreter can’t optimize switch block.
The End. :)

No comments: