[Javascript] Efficiency of innerHTML over DOM tree manipulation

Rakesh Pai rakeshpai at gmail.com
Wed Jun 28 07:52:04 CDT 2006


I'm not sure which technique would be faster. In any case, performance
would be heavily dependent on the browser's engine. My guess would be
that Trillian (IE) would be faster with innerHTML, and Gecko (FF, NS)
would be faster with DOM manipulation. Of course, don't take my word
for it - you will have to try getting your hands on some sort of test
results.

My thoughts:

When using innerHTML, never call element.innerHTML += "string" in a
loop. It causes a huge performance loss. Instead, create a huge string
and finally set element.innerHTML = builtString. Personally, I don't
prefer using innerHTML because there is scope for errors especially if
you are a 'markup-purity' sucker, and the code doesn't look clean with
innerHTML.

When using DOM manipulation, similar to using the innerHTML property,
never append your nodes to the document in a loop. Instead,
createDocumentFragment, or simply create a node (or set of nodes)
first, and finally append it to the document after exiting the loop.
Though DOM manipulation might seem more verbose, you'll quickly
discover that it is easier to maintain code written using this
technique as opposed to innerHTML.

An after thought: element.innerHTML is not really supported (at least
by the spec) if the doctype of your page is XHTML or XML. So, if you
are planning to make a site that is likely to live longer than a
couple of years, you should probably avoid innerHTML. (It's a
different issue that almost every modern browser supports innerHTML
with an XHTML doctype, but that is obviously wrong, and not guranteed
to work in future browsers.)

On 6/28/06, Steve Clay <sclay at ufl.edu> wrote:
> Wednesday, June 28, 2006, 7:15:32 AM, Matt wrote:
> > Is either method more efficient than the other?
>
> Browsers are Really Good at parsing markup so innerHTML is almost always
> faster. That said, I would recommend adding all the needed elements in one
> shot rather than calling innerHTML in a loop. Also, if you're building
> markup by concatenating strings in a loop, you might get better performance
> by adding each chunk to an array then joining at the end:
>
> markup = [];
> while(loop) {
>   markup.push('<!-- markup here-->');
> }
> target.innerHTML = markup.join('');
>
> BTW, the "standard version" of innerHTML is a bit messy and way
> undersupported: http://www.grauw.nl/blog/entry/179
>
> Steve
> --
> http://mrclay.org/
>
> _______________________________________________
> Javascript mailing list
> Javascript at LaTech.edu
> https://lists.LaTech.edu/mailman/listinfo/javascript
>


-- 
Rakesh Pai
Mumbai, India.
rakesh.pai at gmail.com
http://piecesofrakesh.blogspot.com/



More information about the Javascript mailing list