A recent question on Stack Overflow posed a common question concerning DOM insertion and specifically the dire performance of IE6 when using innerHTML to parse a large amount of HTML markup. Head over there to read the question for yourself. I thought it worth sharing my solution; an asynchronous function to add large quantities of HTML to a page without locking up the browser:

function asyncInnerHTML(HTML, callback) {
    var temp = document.createElement('div'),
        frag = document.createDocumentFragment();
    temp.innerHTML = HTML;
            setTimeout(arguments.callee, 0);
        } else {

The large amount of HTML, on its own, is no problem; it’s adding it to the DOM which creates a delay. To avoid this, the HTML is first added to an outside-of-DOM div, the child nodes of which are then recursively added to a document fragment. The fragment is passed to the callback for insertion – or whatever else you may want to do.

The timeout of zero is just to let the browser catch a breath before continuing; doing so means that the user can continue to interact with the page while this all occurs.

Here’s an example:

var htmlStr = '<div><p>...</p><p>...</p><div><div>...</div>';
asyncInnerHTML(htmlStr, function(fragment){
    // You can treat 'fragment' as a regular node.

Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!