Vishful thinking…

Writing better javascript – Part 3

Posted in javascript by viswaug on November 18, 2008

Writing AJAX applications involves a lot of scenarios where the data sent from the server to the browser needs to be inserted into the web page as appropriate HTML elements. When using JavaScript to dynamically inject contents into your HTML page, it is better to use the ‘innerHTML’ property of the DOM element and injecting all the contents as a string into the HTML page. This method even though seemingly ugly is faster than using DOM manipulation methods on the document object like ‘document.createElement(…)’ and ‘element.appendChild(…)’ etc to insert dynamic contents.

Check out the benchmarks on the performance benefits of using the ‘innerHTML’ property over the DOM manipulation methods here at QuirksMode. If you are a bigger stickler for performance and the gains from using ‘innerHTML’ doesn’t satisfy you, then you might consider using the ‘replaceHTML’ function below as per the suggestions posted here.

function replaceHtml(el, html) {
	var oldEl = typeof el === "string" ? document.getElementById(el) : el;
	/*@cc_on // Pure innerHTML is slightly faster in IE
		oldEl.innerHTML = html;
		return oldEl;
	var newEl = oldEl.cloneNode(false);
	newEl.innerHTML = html;
	oldEl.parentNode.replaceChild(newEl, oldEl);
	/* Since we just removed the old element from the DOM, return a reference
	to the new element, which can be used to restore variable references. */
	return newEl;

One Response

Subscribe to comments with RSS.

  1. Ronan said, on November 19, 2008 at 3:59 pm

    Also, once finished using oldEl, it should be nullified.

    Any object retrieved from the DOM, via calls like: document.getElementById(el) need to be nullified once finished being used otherwise these are JavaScript Memory leaks.

    These are more serious when using IE6.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: