Caching the DOM element
DIV1 element
DIV2 element
DIV3 element
Slow:function nodomcache() { var count=1000; for(var i=0;i<count;i++) { var value1=document.getElementById("div1").innerHTML; var value2=document.getElementById("div2").innerHTML; var value3=document.getElementById("div3").innerHTML; } }Faster:
function domcache() { var count=1000; var ele1=document.getElementById("div1"); var ele2=document.getElementById("div2"); var ele3=document.getElementById("div3"); for(var i=0;i<count;i++) { var value1=ele1.innerHTML; var value2=ele2.innerHTML; var value3=ele3.innerHTML; } }
Rule: Cache the element for better performance. This caching is applicable for all types or variables.
Creating dynamic HTML (appendChild vs innerHTML)
Slow:function appendchildhtml() { var count=100; var tblele=document.createElement("table"); var tblbodyele=document.createElement("tbody"); for(var i=0;i<count;i++) { var trele= document.createElement("tr"); var tdele1= document.createElement("td"); tdele1.appendChild(document.createTextNode(i)) trele.appendChild(tdele1); var tdele2= document.createElement("td"); tdele2.appendChild(document.createTextNode(i)) trele.appendChild(tdele2); tblbodyele.appendChild(trele); } tblele.appendChild(tblbodyele); document.getElementById("result1").appendChild(tblele); }Faster:
function innerhtml() { var count=100; var strHTML=""; strHTML+="<table>"; for(var i=0;i<count;i++) { strHTML+="<tr>"; strHTML+="<td>"; strHTML+=i; strHTML+="</td>"; strHTML+="<td>"; strHTML+=i; strHTML+="</td>"; strHTML+="</tr>"; } strHTML+="</table>"; document.getElementById("result2").innerHTML=strHTML; }
Rule: Use innerHTML for dynamically adding html content.
No comments:
Post a Comment