Writing better javascript – Part 3
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; };
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.