The following tips can be used to improve sluggish javascript code:
- Avoid using the eval() function.
- Avoid the with construction.
- Minimize repetitive expression evaluation.
- Use simulated hash tables for lookups in large arrays of objects.
- Avoid excessive string concatenation.
- Investigate download performance.
- Avoid multiple document.write() method calls.
- Use global namespace variables to encapsulate your variables, to avoid colisions with other JavaScripts
- Recursion, as elegant as it is, is heavy in js, and it takes longer to execute than regular for or while loops. It can produce stack overflows. Use it lightly.
Source (for more details on why): http://www.devarticles.com/c/a/JavaScript/More-on-Variables-Functions-and-Flow-Control/3/
To check your JavaScript code for best practices you can use jlint:
More lessons learned in the trenches:
- When you user JS to switch classes, the DOM has to redraw and recalculate all the CSS associated with that and the children tags. Try to do it lightly, or try to stick to switching styles as inline inserts, Jquery animations style
- When you need to use setTimeOut, use requestAnimationFrame instead. In a nutshell, it is a way for browsers to give you access to the frames when they refresh stuff, so your updates to the UI will be coordinated with other animations and things going on the UI. Here is an easy to digest example of this usage (or more complicated at the original source https://gist.github.com/1579671 ):
window.requestAnimFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function( callback ){ window.setTimeout(callback, 1000 / 60); }; })();