Ways to optimize your JavaScript and DOM operations

Much credit owed to Joseph Smarr, co-workers, and experience. A lot of these suggestions become noticeably helpful as your application grows larger and adds complexity.

  1. Don't use DOM operations to create nodes. Use parentNode.innerHTML. Example:

    parentNode.innerHTML = "<div>Stuff</div>"

  2. There are exceptions to #1. For instance, don't use innerHTML += to add content, because everything already a part of the dom will be redrawn and images and such will be reloaded. Try this trick instead (there is probably a better way to do this):

    node = document.createElement("div");
    node.innerHTML = "<div>More Stuff</div>";
    parentNode.appendChild(node.childNodes[0]);

  3. Don't use string concatenation. Strings are immutable objects so you are creating new strings each time, an expensive operation.

    Don't do:

    html = "";
    html += "<div>"
    html += "Content"
    html += "</div>"
    parentNode.innerHTML = html;

    Instead do this:

    html = [];
    html.push("<div>")
    html.push("Content")
    html.push("</div>")
    parentNode.innerHTML = html.join("");

    "".concat() is an alternative that is faster than +=.

  4. Give the browser room to breathe after an intensive DOM operations with setTimeout. Say you've just pushed a lot of new nodes into the dom and you want to start an animation revealing these new nodes with your favorite JavaScript library.

    Don't do this:

    parentNode.innerHTML = html.join(""); //adding a complex dom structure
    animation.play(args);

    Instead try:

    parentNode.innerHTML = html.join(""); //adding a complex dom structure
    setTimeout(function(){
        animation.play(args);
    },0);

    This allows the browser to catch up, so to speak.

  5. Keep your JavaScript file size small. Avoid complicated design patterns that bloat your code. Browsers have to interpret all that JavaScript and it takes time. Joel disagrees with this.

  6. Load JavaScript not initially needed when it is needed. Similar to Just-In-Time concepts. JavaScript libraries like Dojo have methods such as dojo.require() or dojo.requireIf() that can be a great help at keeping your file size down.

  7. Compress your JavaScript. Some people disagree.

  8. gzipping helps.

  9. Use Firebug and Yslow to profile your application.

changed September 19, 2007