2.盡量把內(nèi)容集中起來(lái)一次更新。如果不是特別需要有HTML的內(nèi)容,盡量使用innerText代替innerHTML Slow: divUpdate.innerHTML = ""; for ( var i=0; i<100; i++ ) { divUpdate.innerHTML += "This is a slower method! "; } Fast: var str=""; for ( var i=0; i<100; i++ ) { str += "This is faster because it uses a string! "; } divUpdate.innerHTML = str;
3.更新文本內(nèi)容時(shí)盡量使用innerText而不是DOM的createTextNode Slow: var node; for (var i=0; i<100; i++) { node = document.createElement( "SPAN" ); node.appendChild( document.createTextNode( " Using createTextNode() " ) ); divUpdate.appendChild( node ); } Fast: var node; for (var i=0; i<100; i++) { node = document.createElement( "SPAN" ); node.innerText = " Using innerText property "; divUpdate.appendChild( node ); }
4.盡量使用createElement 和 insertAdjacentElement 方法,而不是 insertAdjacentHTML Slow: for (var i=0; i<100; i++) { divUpdate.insertAdjacentHTML( "beforeEnd", " Uses insertAdjacentHTML() " ); } Fast: var node; for (var i=0; i<100; i++) { node = document.createElement( "SPAN" ); node.innerText = " Uses insertAdjacentElement() "; divUpdate.insertAdjacentElement( "beforeEnd", node ); }
5.在數(shù)目巨大的情況下,盡量使用innerHTML 來(lái)添加項(xiàng) Slow: var opt; divUpdate.innerHTML = ""; for (var i=0; i<1000; i++) { opt = document.createElement( "OPTION" ); selUpdate.options.add( opt ); opt.innerText = "Item " + i; } Fast: var str=""; divUpdate.innerHTML = str; Faster: var arr = new Array(1000); for (var i=0; i<1000; i++) { arr[i] = ""; } divUpdate.innerHTML = ""; 6.使用DOM來(lái)創(chuàng)建表格比TOM(insertRow,insertCell)好的多 Slow: var row; var cell; for (var i=0; i<10
0; i++) { row = tblUpdate.insertRow(); for (var j=0; j<10; j++) { cell = row.insertCell(); cell.innerText = "Row " + i + ", Cell " + j; } } Fast: var row; var cell; var tbody = tblUpdate.childNodes[0]; tblUpdate.appendChild( tbody ); for (var i=0; i<100; i++) { row = document.createElement( "TR" ); tbody.appendChild( row ); for (var j=0; j<10; j++) { cell = document.createElement( "TD" ); row.appendChild( cell ); cell.innerText = "Row " + i + ", Cell " + j; } } 7.通用的操作,盡量放在一個(gè)單獨(dú)的外部腳本文件里 8.約束你的動(dòng)態(tài)屬性(指setExpression的用法) 9.使用數(shù)據(jù)綁定來(lái)顯示你的資料,你可以使用排序、過(guò)濾等操作來(lái)提供不同視圖,但只需要訪問(wèn)一次服務(wù)器(減少頻繁訪問(wèn)服務(wù)器的問(wèn)題) 10.不要把自定義的屬性加到document對(duì)象上,這會(huì)使得每次讀取該屬性時(shí)進(jìn)行額外的重算。推薦加在window對(duì)象上 Slow: for (var i=0; i<1000; i++) { var tmp; window.document.myProperty = "Item "+i; tmp = window.document.myProperty; } Fast: for (var i=0; i<1000; i++) { var tmp; window.myProperty = "Item "+i; tmp = window.myProperty; } 11.盡量直接使用style對(duì)象來(lái)改變HTML對(duì)象外觀,而不是className或者跟clas關(guān)聯(lián)的styleSheet對(duì)象 12.在訪問(wèn)textrange對(duì)象的父對(duì)象(指parentElement方法的返回值)時(shí),先collapse合并range,尤其是復(fù)雜的range 13.先插入對(duì)象,然后添加它的內(nèi)容 Slow (1).create